1
0

youtube.py 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import collections
  4. import hashlib
  5. import itertools
  6. import json
  7. import os.path
  8. import random
  9. import re
  10. import string
  11. import time
  12. import traceback
  13. from .common import InfoExtractor, SearchInfoExtractor
  14. from ..compat import (
  15. compat_chr,
  16. compat_HTTPError,
  17. compat_map as map,
  18. compat_dict as o_dict,
  19. compat_dict_items as dict_items,
  20. compat_str,
  21. compat_urllib_parse,
  22. compat_urllib_parse_parse_qs as compat_parse_qs,
  23. compat_urllib_parse_unquote_plus,
  24. compat_urllib_parse_urlparse,
  25. compat_zip as zip,
  26. )
  27. from ..jsinterp import JSInterpreter
  28. from ..utils import (
  29. bug_reports_message,
  30. clean_html,
  31. dict_get,
  32. error_to_compat_str,
  33. ExtractorError,
  34. filter_dict,
  35. float_or_none,
  36. get_first,
  37. extract_attributes,
  38. get_element_by_attribute,
  39. int_or_none,
  40. join_nonempty,
  41. js_to_json,
  42. LazyList,
  43. merge_dicts,
  44. mimetype2ext,
  45. NO_DEFAULT,
  46. parse_codecs,
  47. parse_count,
  48. parse_duration,
  49. parse_qs,
  50. qualities,
  51. remove_end,
  52. remove_start,
  53. smuggle_url,
  54. str_or_none,
  55. str_to_int,
  56. T,
  57. traverse_obj,
  58. try_call,
  59. try_get,
  60. txt_or_none,
  61. unescapeHTML,
  62. unified_strdate,
  63. unsmuggle_url,
  64. update_url,
  65. update_url_query,
  66. url_or_none,
  67. urlencode_postdata,
  68. urljoin,
  69. variadic,
  70. )
  71. class YoutubeBaseInfoExtractor(InfoExtractor):
  72. """Provide base functions for Youtube extractors"""
  73. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  74. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  75. _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
  76. _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
  77. _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
  78. _NETRC_MACHINE = 'youtube'
  79. # If True it will raise an error if no login info is provided
  80. _LOGIN_REQUIRED = False
  81. _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM)'
  82. # priority order for now
  83. _INNERTUBE_CLIENTS = o_dict((
  84. # Doesn't require a PoToken for some reason: thx yt-dlp/yt-dlp#14693
  85. ('android_sdkless', {
  86. 'INNERTUBE_CONTEXT': {
  87. 'client': {
  88. 'clientName': 'ANDROID',
  89. 'clientVersion': '20.10.38',
  90. 'userAgent': 'com.google.android.youtube/20.10.38 (Linux; U; Android 11) gzip',
  91. 'osName': 'Android',
  92. 'osVersion': '11',
  93. },
  94. },
  95. 'INNERTUBE_CONTEXT_CLIENT_NAME': 3,
  96. 'REQUIRE_JS_PLAYER': False,
  97. 'WITH_COOKIES': False,
  98. }),
  99. ('ios', {
  100. 'INNERTUBE_CONTEXT': {
  101. 'client': {
  102. 'clientName': 'IOS',
  103. 'clientVersion': '20.10.4',
  104. 'deviceMake': 'Apple',
  105. 'deviceModel': 'iPhone16,2',
  106. 'userAgent': 'com.google.ios.youtube/20.10.4 (iPhone16,2; U; CPU iOS 18_3_2 like Mac OS X;)',
  107. 'osName': 'iPhone',
  108. 'osVersion': '18.3.2.22D82',
  109. },
  110. },
  111. 'INNERTUBE_CONTEXT_CLIENT_NAME': 5,
  112. 'REQUIRE_PO_TOKEN': True,
  113. 'REQUIRE_JS_PLAYER': False,
  114. 'WITH_COOKIES': False,
  115. }),
  116. # mweb has 'ultralow' formats
  117. # See: https://github.com/yt-dlp/yt-dlp/pull/557
  118. ('mweb', {
  119. 'INNERTUBE_CONTEXT': {
  120. 'client': {
  121. 'clientName': 'MWEB',
  122. 'clientVersion': '2.2.20250925.01.00',
  123. # mweb previously did not require PO Token with this UA
  124. 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 16_7_10 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1,gzip(gfe)',
  125. },
  126. },
  127. 'INNERTUBE_CONTEXT_CLIENT_NAME': 2,
  128. 'REQUIRE_PO_TOKEN': True,
  129. }),
  130. ('tv_downgraded', {
  131. 'INNERTUBE_CONTEXT': {
  132. 'client': {
  133. 'clientName': 'TVHTML5',
  134. 'clientVersion': '4', # avoids SABR formats, thx yt-dlp/yt-dlp#14887
  135. 'userAgent': 'Mozilla/5.0 (ChromiumStylePlatform) Cobalt/Version',
  136. },
  137. },
  138. 'INNERTUBE_CONTEXT_CLIENT_NAME': 7,
  139. 'SUPPORTS_COOKIES': True,
  140. }),
  141. ('tv', {
  142. 'INNERTUBE_CONTEXT': {
  143. 'client': {
  144. 'clientName': 'TVHTML5',
  145. 'clientVersion': '7.20250312.16.00',
  146. # See: https://github.com/youtube/cobalt/blob/main/cobalt/browser/user_agent/user_agent_platform_info.cc#L506
  147. 'userAgent': 'Mozilla/5.0 (ChromiumStylePlatform) Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Unknown, Unknown)',
  148. },
  149. },
  150. 'INNERTUBE_CONTEXT_CLIENT_NAME': 7,
  151. }),
  152. ('web', {
  153. 'INNERTUBE_CONTEXT': {
  154. 'client': {
  155. 'clientName': 'WEB',
  156. 'clientVersion': '2.20250925.01.00',
  157. 'userAgent': 'Mozilla/5.0',
  158. },
  159. },
  160. 'INNERTUBE_CONTEXT_CLIENT_NAME': 1,
  161. 'REQUIRE_PO_TOKEN': True,
  162. }),
  163. ('web_embedded', {
  164. 'INNERTUBE_CONTEXT': {
  165. 'client': {
  166. 'clientName': 'WEB_EMBEDDED_PLAYER',
  167. 'clientVersion': '1.20250923.21.00',
  168. 'embedUrl': 'https://www.youtube.com/', # Can be any valid URL
  169. },
  170. },
  171. 'INNERTUBE_CONTEXT_CLIENT_NAME': 56,
  172. 'SUPPORTS_COOKIES': True,
  173. }),
  174. # Safari UA returns pre-merged video+audio 144p/240p/360p/720p/1080p HLS formats
  175. ('web_safari', {
  176. 'INNERTUBE_CONTEXT': {
  177. 'client': {
  178. 'clientName': 'WEB',
  179. 'clientVersion': '2.20250925.01.00',
  180. 'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15,gzip(gfe)',
  181. },
  182. },
  183. 'INNERTUBE_CONTEXT_CLIENT_NAME': 1,
  184. 'SUPPORTS_COOKIES': True,
  185. 'REQUIRE_PO': True,
  186. }),
  187. # This client now requires sign-in for every video
  188. ('web_creator', {
  189. 'INNERTUBE_CONTEXT': {
  190. 'client': {
  191. 'clientName': 'WEB_CREATOR',
  192. 'clientVersion': '1.20250922.03.00',
  193. },
  194. },
  195. 'INNERTUBE_CONTEXT_CLIENT_NAME': 62,
  196. 'REQUIRE_AUTH': True,
  197. 'SUPPORTS_COOKIES': True,
  198. 'WITH_COOKIES': True,
  199. }),
  200. ))
  201. def _login(self):
  202. """
  203. Attempt to log in to YouTube.
  204. True is returned if successful or skipped.
  205. False is returned if login failed.
  206. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  207. """
  208. username, password = self._get_login_info()
  209. # No authentication to be performed
  210. if username is None:
  211. if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
  212. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  213. return True
  214. login_page = self._download_webpage(
  215. self._LOGIN_URL, None,
  216. note='Downloading login page',
  217. errnote='unable to fetch login page', fatal=False)
  218. if login_page is False:
  219. return
  220. login_form = self._hidden_inputs(login_page)
  221. def req(url, f_req, note, errnote):
  222. data = login_form.copy()
  223. data.update({
  224. 'pstMsg': 1,
  225. 'checkConnection': 'youtube',
  226. 'checkedDomains': 'youtube',
  227. 'hl': 'en',
  228. 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
  229. 'f.req': json.dumps(f_req),
  230. 'flowName': 'GlifWebSignIn',
  231. 'flowEntry': 'ServiceLogin',
  232. # TODO: reverse actual botguard identifier generation algo
  233. 'bgRequest': '["identifier",""]',
  234. })
  235. return self._download_json(
  236. url, None, note=note, errnote=errnote,
  237. transform_source=lambda s: re.sub(r'^[^[]*', '', s),
  238. fatal=False,
  239. data=urlencode_postdata(data), headers={
  240. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  241. 'Google-Accounts-XSRF': 1,
  242. })
  243. def warn(message):
  244. self._downloader.report_warning(message)
  245. lookup_req = [
  246. username,
  247. None, [], None, 'US', None, None, 2, False, True,
  248. [
  249. None, None,
  250. [2, 1, None, 1,
  251. 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',
  252. None, [], 4],
  253. 1, [None, None, []], None, None, None, True,
  254. ],
  255. username,
  256. ]
  257. lookup_results = req(
  258. self._LOOKUP_URL, lookup_req,
  259. 'Looking up account info', 'Unable to look up account info')
  260. if lookup_results is False:
  261. return False
  262. user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
  263. if not user_hash:
  264. warn('Unable to extract user hash')
  265. return False
  266. challenge_req = [
  267. user_hash,
  268. None, 1, None, [1, None, None, None, [password, None, True]],
  269. [
  270. None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],
  271. 1, [None, None, []], None, None, None, True,
  272. ]]
  273. challenge_results = req(
  274. self._CHALLENGE_URL, challenge_req,
  275. 'Logging in', 'Unable to log in')
  276. if challenge_results is False:
  277. return
  278. login_res = try_get(challenge_results, lambda x: x[0][5], list)
  279. if login_res:
  280. login_msg = try_get(login_res, lambda x: x[5], compat_str)
  281. warn(
  282. 'Unable to login: %s' % 'Invalid password'
  283. if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
  284. return False
  285. res = try_get(challenge_results, lambda x: x[0][-1], list)
  286. if not res:
  287. warn('Unable to extract result entry')
  288. return False
  289. login_challenge = try_get(res, lambda x: x[0][0], list)
  290. if login_challenge:
  291. challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
  292. if challenge_str == 'TWO_STEP_VERIFICATION':
  293. # SEND_SUCCESS - TFA code has been successfully sent to phone
  294. # QUOTA_EXCEEDED - reached the limit of TFA codes
  295. status = try_get(login_challenge, lambda x: x[5], compat_str)
  296. if status == 'QUOTA_EXCEEDED':
  297. warn('Exceeded the limit of TFA codes, try later')
  298. return False
  299. tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
  300. if not tl:
  301. warn('Unable to extract TL')
  302. return False
  303. tfa_code = self._get_tfa_info('2-step verification code')
  304. if not tfa_code:
  305. warn(
  306. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  307. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  308. return False
  309. tfa_code = remove_start(tfa_code, 'G-')
  310. tfa_req = [
  311. user_hash, None, 2, None,
  312. [
  313. 9, None, None, None, None, None, None, None,
  314. [None, tfa_code, True, 2],
  315. ]]
  316. tfa_results = req(
  317. self._TFA_URL.format(tl), tfa_req,
  318. 'Submitting TFA code', 'Unable to submit TFA code')
  319. if tfa_results is False:
  320. return False
  321. tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
  322. if tfa_res:
  323. tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
  324. warn(
  325. 'Unable to finish TFA: %s' % 'Invalid TFA code'
  326. if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
  327. return False
  328. check_cookie_url = try_get(
  329. tfa_results, lambda x: x[0][-1][2], compat_str)
  330. else:
  331. CHALLENGES = {
  332. 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
  333. 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
  334. 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
  335. }
  336. challenge = CHALLENGES.get(
  337. challenge_str,
  338. '%s returned error %s.' % (self.IE_NAME, challenge_str))
  339. warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
  340. return False
  341. else:
  342. check_cookie_url = try_get(res, lambda x: x[2], compat_str)
  343. if not check_cookie_url:
  344. warn('Unable to extract CheckCookie URL')
  345. return False
  346. check_cookie_results = self._download_webpage(
  347. check_cookie_url, None, 'Checking cookie', fatal=False)
  348. if check_cookie_results is False:
  349. return False
  350. if 'https://myaccount.google.com/' not in check_cookie_results:
  351. warn('Unable to log in')
  352. return False
  353. return True
  354. def _initialize_consent(self):
  355. cookies = self._get_cookies('https://www.youtube.com/')
  356. if cookies.get('__Secure-3PSID'):
  357. return
  358. socs = cookies.get('SOCS')
  359. if socs and not socs.value.startswith('CAA'): # not consented
  360. return
  361. self._set_cookie('.youtube.com', 'SOCS', 'CAI', secure=True) # accept all (required for mixes)
  362. def _real_initialize(self):
  363. self._initialize_consent()
  364. if self._downloader is None:
  365. return
  366. if not self._login():
  367. return
  368. _DEFAULT_API_DATA = {'context': _INNERTUBE_CLIENTS['web']['INNERTUBE_CONTEXT']}
  369. _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
  370. _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
  371. _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
  372. _SAPISID = None
  373. def _generate_sapisidhash_header(self, origin='https://www.youtube.com'):
  374. time_now = round(time.time())
  375. if self._SAPISID is None:
  376. yt_cookies = self._get_cookies('https://www.youtube.com')
  377. # Sometimes SAPISID cookie isn't present but __Secure-3PAPISID is.
  378. # See: https://github.com/yt-dlp/yt-dlp/issues/393
  379. sapisid_cookie = dict_get(
  380. yt_cookies, ('__Secure-3PAPISID', 'SAPISID'))
  381. if sapisid_cookie and sapisid_cookie.value:
  382. self._SAPISID = sapisid_cookie.value
  383. self.write_debug('Extracted SAPISID cookie')
  384. # SAPISID cookie is required if not already present
  385. if not yt_cookies.get('SAPISID'):
  386. self.write_debug('Copying __Secure-3PAPISID cookie to SAPISID cookie')
  387. self._set_cookie(
  388. '.youtube.com', 'SAPISID', self._SAPISID, secure=True, expire_time=time_now + 3600)
  389. else:
  390. self._SAPISID = False
  391. if not self._SAPISID:
  392. return None
  393. # SAPISIDHASH algorithm from https://stackoverflow.com/a/32065323
  394. sapisidhash = hashlib.sha1(
  395. '{0} {1} {2}'.format(time_now, self._SAPISID, origin).encode('utf-8')).hexdigest()
  396. return 'SAPISIDHASH {0}_{1}'.format(time_now, sapisidhash)
  397. def _call_api(self, ep, query, video_id, fatal=True, headers=None,
  398. note='Downloading API JSON'):
  399. data = self._DEFAULT_API_DATA.copy()
  400. data.update(query)
  401. real_headers = {'content-type': 'application/json'}
  402. if headers:
  403. real_headers.update(headers)
  404. # was: 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
  405. api_key = self.get_param('youtube_innertube_key')
  406. return self._download_json(
  407. 'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
  408. note=note, errnote='Unable to download API page',
  409. data=json.dumps(data).encode('utf8'), fatal=fatal,
  410. headers=real_headers, query=filter_dict({
  411. 'key': api_key,
  412. 'prettyPrint': 'false',
  413. }))
  414. def _extract_yt_initial_data(self, video_id, webpage):
  415. return self._parse_json(
  416. self._search_regex(
  417. (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
  418. self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
  419. video_id)
  420. def _extract_visitor_data(self, *args):
  421. """
  422. Extract visitorData from an API response or ytcfg
  423. Appears to be used to track session state
  424. """
  425. visitor_data = self.get_param('youtube_visitor_data')
  426. if visitor_data:
  427. return visitor_data
  428. return get_first(
  429. args, (('VISITOR_DATA',
  430. ('INNERTUBE_CONTEXT', 'client', 'visitorData'),
  431. ('responseContext', 'visitorData')),
  432. T(compat_str)))
  433. # @functools.cached_property
  434. def is_authenticated(self, _cache={}):
  435. if self not in _cache:
  436. _cache[self] = bool(self._generate_sapisidhash_header())
  437. return _cache[self]
  438. def _extract_ytcfg(self, video_id, webpage):
  439. ytcfg = self._search_json(
  440. r'ytcfg\.set\s*\(', webpage, 'ytcfg', video_id,
  441. end_pattern=r'\)\s*;', default={})
  442. traverse_obj(ytcfg, (
  443. 'INNERTUBE_CONTEXT', 'client', 'configInfo',
  444. T(lambda x: x.pop('appInstallData', None))))
  445. return ytcfg
  446. def _extract_video(self, renderer):
  447. video_id = renderer['videoId']
  448. title = try_get(
  449. renderer,
  450. (lambda x: x['title']['runs'][0]['text'],
  451. lambda x: x['title']['simpleText'],
  452. lambda x: x['headline']['simpleText']), compat_str)
  453. description = try_get(
  454. renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
  455. compat_str)
  456. duration = parse_duration(try_get(
  457. renderer, lambda x: x['lengthText']['simpleText'], compat_str))
  458. view_count_text = try_get(
  459. renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
  460. view_count = str_to_int(self._search_regex(
  461. r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
  462. 'view count', default=None))
  463. uploader = try_get(
  464. renderer,
  465. (lambda x: x['ownerText']['runs'][0]['text'],
  466. lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
  467. return {
  468. '_type': 'url',
  469. 'ie_key': YoutubeIE.ie_key(),
  470. 'id': video_id,
  471. 'url': video_id,
  472. 'title': title,
  473. 'description': description,
  474. 'duration': duration,
  475. 'view_count': view_count,
  476. 'uploader': uploader,
  477. }
  478. @staticmethod
  479. def _extract_thumbnails(data, *path_list, **kw_final_key):
  480. """
  481. Extract thumbnails from thumbnails dict
  482. @param path_list: path list to level that contains 'thumbnails' key
  483. """
  484. final_key = kw_final_key.get('final_key', 'thumbnails')
  485. return traverse_obj(data, ((
  486. tuple(variadic(path) + (final_key, Ellipsis)
  487. for path in path_list or [()])), {
  488. 'url': ('url', T(url_or_none),
  489. # Sometimes youtube gives a wrong thumbnail URL. See:
  490. # https://github.com/yt-dlp/yt-dlp/issues/233
  491. # https://github.com/ytdl-org/youtube-dl/issues/28023
  492. T(lambda u: update_url(u, query=None) if u and 'maxresdefault' in u else u)),
  493. 'height': ('height', T(int_or_none)),
  494. 'width': ('width', T(int_or_none)),
  495. }, T(lambda t: t if t.get('url') else None)))
  496. def _search_results(self, query, params):
  497. data = {
  498. 'context': {
  499. 'client': {
  500. 'clientName': 'WEB',
  501. 'clientVersion': '2.20201021.03.00',
  502. },
  503. },
  504. 'query': query,
  505. }
  506. if params:
  507. data['params'] = params
  508. for page_num in itertools.count(1):
  509. search = self._download_json(
  510. 'https://www.youtube.com/youtubei/v1/search',
  511. video_id='query "%s"' % query,
  512. note='Downloading page %s' % page_num,
  513. errnote='Unable to download API page', fatal=False,
  514. data=json.dumps(data).encode('utf8'),
  515. query={
  516. # 'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  517. 'prettyPrint': 'false',
  518. },
  519. headers={'content-type': 'application/json'})
  520. if not search:
  521. break
  522. slr_contents = traverse_obj(
  523. search,
  524. ('contents', 'twoColumnSearchResultsRenderer', 'primaryContents',
  525. 'sectionListRenderer', 'contents'),
  526. ('onResponseReceivedCommands', 0, 'appendContinuationItemsAction',
  527. 'continuationItems'),
  528. expected_type=list)
  529. if not slr_contents:
  530. break
  531. for video in traverse_obj(
  532. slr_contents,
  533. (Ellipsis, 'itemSectionRenderer', 'contents',
  534. Ellipsis, 'videoRenderer',
  535. T(lambda v: v if v.get('videoId') else None))):
  536. yield self._extract_video(video)
  537. token = traverse_obj(
  538. slr_contents,
  539. (-1, 'continuationItemRenderer', 'continuationEndpoint',
  540. 'continuationCommand', 'token', T(compat_str)))
  541. if not token:
  542. break
  543. data['continuation'] = token
  544. @staticmethod
  545. def _owner_endpoints_path():
  546. return [
  547. Ellipsis,
  548. lambda k, _: k.endswith('SecondaryInfoRenderer'),
  549. ('owner', 'videoOwner'), 'videoOwnerRenderer', 'title',
  550. 'runs', Ellipsis]
  551. def _extract_channel_id(self, webpage, videodetails={}, metadata={}, renderers=[]):
  552. channel_id = None
  553. if any((videodetails, metadata, renderers)):
  554. channel_id = (
  555. traverse_obj(videodetails, 'channelId')
  556. or traverse_obj(metadata, 'externalChannelId', 'externalId')
  557. or traverse_obj(renderers,
  558. self._owner_endpoints_path() + [
  559. 'navigationEndpoint', 'browseEndpoint', 'browseId'],
  560. get_all=False)
  561. )
  562. return channel_id or self._html_search_meta(
  563. 'channelId', webpage, 'channel id', default=None)
  564. def _extract_author_var(self, webpage, var_name,
  565. videodetails={}, metadata={}, renderers=[]):
  566. result = None
  567. paths = {
  568. # (HTML, videodetails, metadata, renderers)
  569. 'name': ('content', 'author', (('ownerChannelName', None), 'title'), ['text']),
  570. 'url': ('href', 'ownerProfileUrl', 'vanityChannelUrl',
  571. ['navigationEndpoint', 'browseEndpoint', 'canonicalBaseUrl']),
  572. }
  573. if any((videodetails, metadata, renderers)):
  574. result = (
  575. traverse_obj(videodetails, paths[var_name][1], get_all=False)
  576. or traverse_obj(metadata, paths[var_name][2], get_all=False)
  577. or traverse_obj(renderers,
  578. self._owner_endpoints_path() + paths[var_name][3],
  579. get_all=False)
  580. )
  581. return result or traverse_obj(
  582. extract_attributes(self._search_regex(
  583. r'''(?s)(<link\b[^>]+\bitemprop\s*=\s*("|')%s\2[^>]*>)'''
  584. % re.escape(var_name),
  585. get_element_by_attribute('itemprop', 'author', webpage or '') or '',
  586. 'author link', default='')),
  587. paths[var_name][0])
  588. @staticmethod
  589. def _yt_urljoin(url_or_path):
  590. return urljoin('https://www.youtube.com', url_or_path)
  591. def _extract_uploader_id(self, uploader_url):
  592. return self._search_regex(
  593. r'/(?:(?:channel|user)/|(?=@))([^/?&#]+)', uploader_url or '',
  594. 'uploader id', default=None)
  595. class YoutubeIE(YoutubeBaseInfoExtractor):
  596. IE_DESC = 'YouTube.com'
  597. _INVIDIOUS_SITES = (
  598. # invidious-redirect websites
  599. r'(?:www\.)?redirect\.invidious\.io',
  600. r'(?:(?:www|dev)\.)?invidio\.us',
  601. # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
  602. r'(?:(?:www|no)\.)?invidiou\.sh',
  603. r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
  604. r'(?:www\.)?invidious\.kabi\.tk',
  605. r'(?:www\.)?invidious\.13ad\.de',
  606. r'(?:www\.)?invidious\.mastodon\.host',
  607. r'(?:www\.)?invidious\.zapashcanon\.fr',
  608. r'(?:www\.)?(?:invidious(?:-us)?|piped)\.kavin\.rocks',
  609. r'(?:www\.)?invidious\.tinfoil-hat\.net',
  610. r'(?:www\.)?invidious\.himiko\.cloud',
  611. r'(?:www\.)?invidious\.reallyancient\.tech',
  612. r'(?:www\.)?invidious\.tube',
  613. r'(?:www\.)?invidiou\.site',
  614. r'(?:www\.)?invidious\.site',
  615. r'(?:www\.)?invidious\.xyz',
  616. r'(?:www\.)?invidious\.nixnet\.xyz',
  617. r'(?:www\.)?invidious\.048596\.xyz',
  618. r'(?:www\.)?invidious\.drycat\.fr',
  619. r'(?:www\.)?inv\.skyn3t\.in',
  620. r'(?:www\.)?tube\.poal\.co',
  621. r'(?:www\.)?tube\.connect\.cafe',
  622. r'(?:www\.)?vid\.wxzm\.sx',
  623. r'(?:www\.)?vid\.mint\.lgbt',
  624. r'(?:www\.)?vid\.puffyan\.us',
  625. r'(?:www\.)?yewtu\.be',
  626. r'(?:www\.)?yt\.elukerio\.org',
  627. r'(?:www\.)?yt\.lelux\.fi',
  628. r'(?:www\.)?invidious\.ggc-project\.de',
  629. r'(?:www\.)?yt\.maisputain\.ovh',
  630. r'(?:www\.)?ytprivate\.com',
  631. r'(?:www\.)?invidious\.13ad\.de',
  632. r'(?:www\.)?invidious\.toot\.koeln',
  633. r'(?:www\.)?invidious\.fdn\.fr',
  634. r'(?:www\.)?watch\.nettohikari\.com',
  635. r'(?:www\.)?invidious\.namazso\.eu',
  636. r'(?:www\.)?invidious\.silkky\.cloud',
  637. r'(?:www\.)?invidious\.exonip\.de',
  638. r'(?:www\.)?invidious\.riverside\.rocks',
  639. r'(?:www\.)?invidious\.blamefran\.net',
  640. r'(?:www\.)?invidious\.moomoo\.de',
  641. r'(?:www\.)?ytb\.trom\.tf',
  642. r'(?:www\.)?yt\.cyberhost\.uk',
  643. r'(?:www\.)?kgg2m7yk5aybusll\.onion',
  644. r'(?:www\.)?qklhadlycap4cnod\.onion',
  645. r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
  646. r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
  647. r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
  648. r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
  649. r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
  650. r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
  651. r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
  652. r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
  653. r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
  654. r'(?:www\.)?hpniueoejy4opn7bc4ftgazyqjoeqwlvh2uiku2xqku6zpoa4bf5ruid\.onion',
  655. )
  656. _VALID_URL = r"""(?x)^
  657. (
  658. (?:https?://|//) # http(s):// or protocol-independent URL
  659. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
  660. (?:www\.)?deturl\.com/www\.youtube\.com|
  661. (?:www\.)?pwnyoutube\.com|
  662. (?:www\.)?hooktube\.com|
  663. (?:www\.)?yourepeat\.com|
  664. tube\.majestyc\.net|
  665. %(invidious)s|
  666. youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
  667. (?:.*?\#/)? # handle anchor (#/) redirect urls
  668. (?: # the various things that can precede the ID:
  669. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  670. |shorts/
  671. |(?: # or the v= param in all its forms
  672. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  673. (?:\?|\#!?) # the params delimiter ? or # or #!
  674. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  675. v=
  676. )
  677. ))
  678. |(?:
  679. youtu\.be| # just youtu.be/xxxx
  680. vid\.plus| # or vid.plus/xxxx
  681. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  682. %(invidious)s
  683. )/
  684. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  685. )
  686. )? # all until now is optional -> you can pass the naked ID
  687. (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  688. (?(1).+)? # if we found the ID, everything can follow
  689. $""" % {
  690. 'invidious': '|'.join(_INVIDIOUS_SITES),
  691. }
  692. _PLAYER_INFO_RE = (
  693. r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/(?:tv-)?player',
  694. r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias(?:_tce)?\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
  695. r'\b(?P<id>vfl[a-zA-Z0-9_-]{6,})\b.*?\.js$',
  696. )
  697. _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'srt', 'vtt')
  698. _GEO_BYPASS = False
  699. IE_NAME = 'youtube'
  700. _TESTS = [
  701. {
  702. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  703. 'info_dict': {
  704. 'id': 'BaW_jenozKc',
  705. 'ext': 'mp4',
  706. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  707. 'uploader': 'Philipp Hagemeister',
  708. 'uploader_id': '@PhilippHagemeister',
  709. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@PhilippHagemeister',
  710. 'channel': 'Philipp Hagemeister',
  711. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  712. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  713. 'upload_date': '20121002',
  714. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  715. 'categories': ['Science & Technology'],
  716. 'tags': ['youtube-dl'],
  717. 'duration': 10,
  718. 'view_count': int,
  719. 'like_count': int,
  720. 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
  721. 'start_time': 1,
  722. 'end_time': 9,
  723. },
  724. },
  725. {
  726. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  727. 'note': 'Embed-only video (#1746)',
  728. 'info_dict': {
  729. 'id': 'yZIXLfi8CZQ',
  730. 'ext': 'mp4',
  731. 'upload_date': '20120608',
  732. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  733. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  734. 'uploader': 'SET India',
  735. 'uploader_id': 'setindia',
  736. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
  737. 'age_limit': 18,
  738. },
  739. 'skip': 'Private video',
  740. },
  741. {
  742. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
  743. 'note': 'Use the first video ID in the URL',
  744. 'info_dict': {
  745. 'id': 'BaW_jenozKc',
  746. 'ext': 'mp4',
  747. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  748. 'uploader': 'Philipp Hagemeister',
  749. 'uploader_id': '@PhilippHagemeister',
  750. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@PhilippHagemeister',
  751. 'upload_date': '20121002',
  752. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  753. 'categories': ['Science & Technology'],
  754. 'tags': ['youtube-dl'],
  755. 'duration': 10,
  756. 'view_count': int,
  757. 'like_count': int,
  758. },
  759. 'params': {
  760. 'skip_download': True,
  761. },
  762. },
  763. {
  764. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  765. 'note': '256k DASH audio (format 141) via DASH manifest',
  766. 'info_dict': {
  767. 'id': 'a9LDPn-MO4I',
  768. 'ext': 'm4a',
  769. 'upload_date': '20121002',
  770. 'uploader_id': '8KVIDEO',
  771. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  772. 'description': '',
  773. 'uploader': '8KVIDEO',
  774. 'title': 'UHDTV TEST 8K VIDEO.mp4',
  775. },
  776. 'params': {
  777. 'youtube_include_dash_manifest': True,
  778. 'format': '141',
  779. },
  780. 'skip': 'format 141 not served any more',
  781. },
  782. # DASH manifest with encrypted signature
  783. {
  784. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  785. 'info_dict': {
  786. 'id': 'IB3lcPjvWLA',
  787. 'ext': 'm4a',
  788. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  789. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  790. 'duration': 244,
  791. 'uploader': 'AfrojackVEVO',
  792. 'uploader_id': '@AfrojackVEVO',
  793. 'upload_date': '20131011',
  794. 'abr': 129.495,
  795. },
  796. 'params': {
  797. 'youtube_include_dash_manifest': True,
  798. 'format': '141/bestaudio[ext=m4a]',
  799. },
  800. },
  801. # Controversy video
  802. {
  803. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  804. 'info_dict': {
  805. 'id': 'T4XJQO3qol8',
  806. 'ext': 'mp4',
  807. 'duration': 219,
  808. 'upload_date': '20100909',
  809. 'uploader': 'Amazing Atheist',
  810. 'uploader_id': '@theamazingatheist',
  811. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@theamazingatheist',
  812. 'title': 'Burning Everyone\'s Koran',
  813. 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms \r\n\r\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
  814. },
  815. },
  816. # Age-gated videos
  817. {
  818. 'note': 'Age-gated video (No vevo, embed allowed)',
  819. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  820. 'info_dict': {
  821. 'id': 'HtVdAasjOgU',
  822. 'ext': 'mp4',
  823. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  824. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  825. 'duration': 142,
  826. 'uploader': 'The Witcher',
  827. 'uploader_id': '@thewitcher',
  828. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@thewitcher',
  829. 'upload_date': '20140605',
  830. 'thumbnail': 'https://i.ytimg.com/vi/HtVdAasjOgU/maxresdefault.jpg',
  831. 'age_limit': 18,
  832. 'categories': ['Gaming'],
  833. 'tags': 'count:17',
  834. 'channel': 'The Witcher',
  835. 'channel_url': 'https://www.youtube.com/channel/UCzybXLxv08IApdjdN0mJhEg',
  836. 'channel_id': 'UCzybXLxv08IApdjdN0mJhEg',
  837. 'view_count': int,
  838. 'like_count': int,
  839. },
  840. },
  841. {
  842. 'note': 'Age-gated video with embed allowed in public site',
  843. 'url': 'https://youtube.com/watch?v=HsUATh_Nc2U',
  844. 'info_dict': {
  845. 'id': 'HsUATh_Nc2U',
  846. 'ext': 'mp4',
  847. 'title': 'Godzilla 2 (Official Video)',
  848. 'description': 'md5:bf77e03fcae5529475e500129b05668a',
  849. 'duration': 177,
  850. 'uploader': 'FlyingKitty',
  851. 'uploader_id': '@FlyingKitty900',
  852. 'upload_date': '20200408',
  853. 'thumbnail': 'https://i.ytimg.com/vi/HsUATh_Nc2U/maxresdefault.jpg',
  854. 'age_limit': 18,
  855. 'categories': ['Entertainment'],
  856. 'tags': ['Flyingkitty', 'godzilla 2'],
  857. 'channel': 'FlyingKitty',
  858. 'channel_url': 'https://www.youtube.com/channel/UCYQT13AtrJC0gsM1far_zJg',
  859. 'channel_id': 'UCYQT13AtrJC0gsM1far_zJg',
  860. 'view_count': int,
  861. 'like_count': int,
  862. },
  863. },
  864. {
  865. 'note': 'Age-gated video embeddable only with clientScreen=EMBED',
  866. 'url': 'https://youtube.com/watch?v=Tq92D6wQ1mg',
  867. 'info_dict': {
  868. 'id': 'Tq92D6wQ1mg',
  869. 'ext': 'mp4',
  870. 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
  871. 'description': 'md5:17eccca93a786d51bc67646756894066',
  872. 'duration': 106,
  873. 'uploader': 'Projekt Melody',
  874. 'uploader_id': '@ProjektMelody',
  875. 'upload_date': '20191227',
  876. 'age_limit': 18,
  877. 'thumbnail': 'https://i.ytimg.com/vi/Tq92D6wQ1mg/sddefault.jpg',
  878. 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
  879. 'categories': ['Entertainment'],
  880. 'channel': 'Projekt Melody',
  881. 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
  882. 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
  883. 'view_count': int,
  884. 'like_count': int,
  885. },
  886. },
  887. {
  888. 'note': 'Non-Age-gated non-embeddable video',
  889. 'url': 'https://youtube.com/watch?v=MeJVWBSsPAY',
  890. 'info_dict': {
  891. 'id': 'MeJVWBSsPAY',
  892. 'ext': 'mp4',
  893. 'title': 'OOMPH! - Such Mich Find Mich (Lyrics)',
  894. 'description': 'Fan Video. Music & Lyrics by OOMPH!.',
  895. 'duration': 210,
  896. 'upload_date': '20130730',
  897. 'uploader': 'Herr Lurik',
  898. 'uploader_id': '@HerrLurik',
  899. 'uploader_url': 'http://www.youtube.com/@HerrLurik',
  900. 'age_limit': 0,
  901. 'thumbnail': 'https://i.ytimg.com/vi/MeJVWBSsPAY/hqdefault.jpg',
  902. 'tags': ['oomph', 'such mich find mich', 'lyrics', 'german industrial', 'musica industrial'],
  903. 'categories': ['Music'],
  904. 'channel': 'Herr Lurik',
  905. 'channel_url': 'https://www.youtube.com/channel/UCdR3RSDPqub28LjZx0v9-aA',
  906. 'channel_id': 'UCdR3RSDPqub28LjZx0v9-aA',
  907. 'artist': 'OOMPH!',
  908. 'view_count': int,
  909. 'like_count': int,
  910. },
  911. },
  912. {
  913. 'note': 'Non-bypassable age-gated video',
  914. 'url': 'https://youtube.com/watch?v=Cr381pDsSsA',
  915. 'only_matching': True,
  916. },
  917. {
  918. 'note': 'Age-gated video only available with authentication (not via embed workaround)',
  919. 'url': 'XgnwCQzjau8',
  920. 'only_matching': True,
  921. 'skip': '''This video has been removed for violating YouTube's Community Guidelines''',
  922. },
  923. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  924. # YouTube Red ad is not captured for creator
  925. {
  926. 'url': '__2ABJjxzNo',
  927. 'info_dict': {
  928. 'id': '__2ABJjxzNo',
  929. 'ext': 'mp4',
  930. 'duration': 266,
  931. 'upload_date': '20100430',
  932. 'uploader_id': '@deadmau5',
  933. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@deadmau5',
  934. 'creator': 'deadmau5',
  935. 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
  936. 'uploader': 'deadmau5',
  937. 'title': 'Deadmau5 - Some Chords (HD)',
  938. 'alt_title': 'Some Chords',
  939. },
  940. 'expected_warnings': [
  941. 'DASH manifest missing',
  942. ],
  943. },
  944. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  945. {
  946. 'url': 'lqQg6PlCWgI',
  947. 'info_dict': {
  948. 'id': 'lqQg6PlCWgI',
  949. 'ext': 'mp4',
  950. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  951. 'description': r're:(?s)(?:.+\s)?HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games\s*',
  952. 'duration': 6085,
  953. 'upload_date': '20150827',
  954. 'uploader_id': '@Olympics',
  955. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@Olympics',
  956. 'uploader': r're:Olympics?',
  957. 'age_limit': 0,
  958. 'thumbnail': 'https://i.ytimg.com/vi/lqQg6PlCWgI/maxresdefault.jpg',
  959. 'categories': ['Sports'],
  960. 'tags': ['Hockey', '2012-07-31', '31 July 2012', 'Riverbank Arena', 'Session', 'Olympics', 'Olympic Games', 'London 2012', '2012 Summer Olympics', 'Summer Games'],
  961. 'channel': 'Olympics',
  962. 'channel_url': 'https://www.youtube.com/channel/UCTl3QQTvqHFjurroKxexy2Q',
  963. 'channel_id': 'UCTl3QQTvqHFjurroKxexy2Q',
  964. 'view_count': int,
  965. 'like_count': int,
  966. },
  967. },
  968. # Non-square pixels
  969. {
  970. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  971. 'info_dict': {
  972. 'id': '_b-2C3KPAM0',
  973. 'ext': 'mp4',
  974. 'stretched_ratio': 16 / 9.,
  975. 'duration': 85,
  976. 'upload_date': '20110310',
  977. 'uploader_id': '@AllenMeow',
  978. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@AllenMeow',
  979. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  980. 'uploader': '孫ᄋᄅ',
  981. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  982. },
  983. },
  984. # url_encoded_fmt_stream_map is empty string
  985. {
  986. 'url': 'qEJwOuvDf7I',
  987. 'info_dict': {
  988. 'id': 'qEJwOuvDf7I',
  989. 'ext': 'webm',
  990. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  991. 'description': '',
  992. 'upload_date': '20150404',
  993. 'uploader_id': 'spbelect',
  994. 'uploader': 'Наблюдатели Петербурга',
  995. },
  996. 'params': {
  997. 'skip_download': 'requires avconv',
  998. },
  999. 'skip': 'This live event has ended.',
  1000. },
  1001. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  1002. {
  1003. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  1004. 'info_dict': {
  1005. 'id': 'FIl7x6_3R5Y',
  1006. 'ext': 'webm',
  1007. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  1008. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  1009. 'duration': 220,
  1010. 'upload_date': '20150625',
  1011. 'uploader_id': 'dorappi2000',
  1012. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  1013. 'uploader': 'dorappi2000',
  1014. 'formats': 'mincount:31',
  1015. },
  1016. 'skip': 'not actual any more',
  1017. },
  1018. # DASH manifest with segment_list
  1019. {
  1020. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  1021. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  1022. 'info_dict': {
  1023. 'id': 'CsmdDsKjzN8',
  1024. 'ext': 'mp4',
  1025. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  1026. 'uploader': 'Airtek',
  1027. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  1028. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  1029. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  1030. },
  1031. 'params': {
  1032. 'youtube_include_dash_manifest': True,
  1033. 'format': '135', # bestvideo
  1034. },
  1035. 'skip': 'This live event has ended.',
  1036. },
  1037. {
  1038. # Multifeed videos (multiple cameras), URL is for Main Camera
  1039. 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
  1040. 'info_dict': {
  1041. 'id': 'jvGDaLqkpTg',
  1042. 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
  1043. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  1044. },
  1045. 'playlist': [{
  1046. 'info_dict': {
  1047. 'id': 'jvGDaLqkpTg',
  1048. 'ext': 'mp4',
  1049. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
  1050. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  1051. 'duration': 10643,
  1052. 'upload_date': '20161111',
  1053. 'uploader': 'Team PGP',
  1054. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  1055. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  1056. },
  1057. }, {
  1058. 'info_dict': {
  1059. 'id': '3AKt1R1aDnw',
  1060. 'ext': 'mp4',
  1061. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
  1062. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  1063. 'duration': 10991,
  1064. 'upload_date': '20161111',
  1065. 'uploader': 'Team PGP',
  1066. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  1067. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  1068. },
  1069. }, {
  1070. 'info_dict': {
  1071. 'id': 'RtAMM00gpVc',
  1072. 'ext': 'mp4',
  1073. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
  1074. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  1075. 'duration': 10995,
  1076. 'upload_date': '20161111',
  1077. 'uploader': 'Team PGP',
  1078. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  1079. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  1080. },
  1081. }, {
  1082. 'info_dict': {
  1083. 'id': '6N2fdlP3C5U',
  1084. 'ext': 'mp4',
  1085. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
  1086. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  1087. 'duration': 10990,
  1088. 'upload_date': '20161111',
  1089. 'uploader': 'Team PGP',
  1090. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  1091. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  1092. },
  1093. }],
  1094. 'params': {
  1095. 'skip_download': True,
  1096. },
  1097. 'skip': 'Not multifeed any more',
  1098. },
  1099. {
  1100. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  1101. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  1102. 'info_dict': {
  1103. 'id': 'gVfLd0zydlo',
  1104. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  1105. },
  1106. 'playlist_count': 2,
  1107. 'skip': 'Not multifeed any more',
  1108. },
  1109. {
  1110. 'url': 'https://vid.plus/FlRa-iH7PGw',
  1111. 'only_matching': True,
  1112. },
  1113. {
  1114. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  1115. 'only_matching': True,
  1116. },
  1117. {
  1118. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  1119. # Also tests cut-off URL expansion in video description (see
  1120. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  1121. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  1122. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  1123. 'info_dict': {
  1124. 'id': 'lsguqyKfVQg',
  1125. 'ext': 'mp4',
  1126. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  1127. 'alt_title': 'Dark Walk',
  1128. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  1129. 'duration': 133,
  1130. 'upload_date': '20151119',
  1131. 'uploader_id': '@IronSoulElf',
  1132. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@IronSoulElf',
  1133. 'uploader': 'IronSoulElf',
  1134. 'creator': r're:Todd Haberman[;,]\s+Daniel Law Heath and Aaron Kaplan',
  1135. 'track': 'Dark Walk',
  1136. 'artist': r're:Todd Haberman[;,]\s+Daniel Law Heath and Aaron Kaplan',
  1137. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  1138. },
  1139. 'params': {
  1140. 'skip_download': True,
  1141. },
  1142. },
  1143. {
  1144. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  1145. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  1146. 'only_matching': True,
  1147. },
  1148. {
  1149. # Video with yt:stretch=17:0
  1150. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  1151. 'info_dict': {
  1152. 'id': 'Q39EVAstoRM',
  1153. 'ext': 'mp4',
  1154. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  1155. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  1156. 'upload_date': '20151107',
  1157. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  1158. 'uploader': 'CH GAMER DROID',
  1159. },
  1160. 'params': {
  1161. 'skip_download': True,
  1162. },
  1163. 'skip': 'This video does not exist.',
  1164. },
  1165. {
  1166. # Video with incomplete 'yt:stretch=16:'
  1167. 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
  1168. 'only_matching': True,
  1169. },
  1170. {
  1171. # Video licensed under Creative Commons
  1172. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  1173. 'info_dict': {
  1174. 'id': 'M4gD1WSo5mA',
  1175. 'ext': 'mp4',
  1176. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  1177. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  1178. 'duration': 721,
  1179. 'upload_date': '20150127',
  1180. 'uploader_id': '@BKCHarvard',
  1181. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@BKCHarvard',
  1182. 'uploader': 'The Berkman Klein Center for Internet & Society',
  1183. 'license': 'Creative Commons Attribution license (reuse allowed)',
  1184. },
  1185. 'params': {
  1186. 'skip_download': True,
  1187. },
  1188. },
  1189. {
  1190. # Channel-like uploader_url
  1191. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  1192. 'info_dict': {
  1193. 'id': 'eQcmzGIKrzg',
  1194. 'ext': 'mp4',
  1195. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  1196. 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
  1197. 'duration': 4060,
  1198. 'upload_date': '20151119',
  1199. 'uploader': 'Bernie Sanders',
  1200. 'uploader_id': '@BernieSanders',
  1201. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@BernieSanders',
  1202. 'license': 'Creative Commons Attribution license (reuse allowed)',
  1203. },
  1204. 'params': {
  1205. 'skip_download': True,
  1206. },
  1207. },
  1208. {
  1209. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  1210. 'only_matching': True,
  1211. },
  1212. {
  1213. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  1214. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  1215. 'only_matching': True,
  1216. },
  1217. {
  1218. # Rental video preview
  1219. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  1220. 'info_dict': {
  1221. 'id': 'uGpuVWrhIzE',
  1222. 'ext': 'mp4',
  1223. 'title': 'Piku - Trailer',
  1224. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  1225. 'upload_date': '20150811',
  1226. 'uploader': 'FlixMatrix',
  1227. 'uploader_id': 'FlixMatrixKaravan',
  1228. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
  1229. 'license': 'Standard YouTube License',
  1230. },
  1231. 'params': {
  1232. 'skip_download': True,
  1233. },
  1234. 'skip': 'This video is not available.',
  1235. },
  1236. {
  1237. # YouTube Red video with episode data
  1238. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  1239. 'info_dict': {
  1240. 'id': 'iqKdEhx-dD4',
  1241. 'ext': 'mp4',
  1242. 'title': 'Isolation - Mind Field (Ep 1)',
  1243. 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
  1244. 'duration': 2085,
  1245. 'upload_date': '20170118',
  1246. 'uploader': 'Vsauce',
  1247. 'uploader_id': '@Vsauce',
  1248. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@Vsauce',
  1249. 'series': 'Mind Field',
  1250. 'season_number': 1,
  1251. 'episode_number': 1,
  1252. },
  1253. 'params': {
  1254. 'skip_download': True,
  1255. },
  1256. 'expected_warnings': [
  1257. 'Skipping DASH manifest',
  1258. ],
  1259. },
  1260. {
  1261. # The following content has been identified by the YouTube community
  1262. # as inappropriate or offensive to some audiences.
  1263. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  1264. 'info_dict': {
  1265. 'id': '6SJNVb0GnPI',
  1266. 'ext': 'mp4',
  1267. 'title': 'Race Differences in Intelligence',
  1268. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  1269. 'duration': 965,
  1270. 'upload_date': '20140124',
  1271. 'uploader': 'New Century Foundation',
  1272. 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
  1273. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
  1274. },
  1275. 'params': {
  1276. 'skip_download': True,
  1277. },
  1278. 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
  1279. },
  1280. {
  1281. # itag 212
  1282. 'url': '1t24XAntNCY',
  1283. 'only_matching': True,
  1284. },
  1285. {
  1286. # geo restricted to JP
  1287. 'url': 'sJL6WA-aGkQ',
  1288. 'only_matching': True,
  1289. },
  1290. {
  1291. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  1292. 'only_matching': True,
  1293. },
  1294. {
  1295. 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
  1296. 'only_matching': True,
  1297. },
  1298. {
  1299. # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
  1300. 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
  1301. 'only_matching': True,
  1302. },
  1303. {
  1304. # DRM protected
  1305. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  1306. 'only_matching': True,
  1307. },
  1308. {
  1309. # Video with unsupported adaptive stream type formats
  1310. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  1311. 'info_dict': {
  1312. 'id': 'Z4Vy8R84T1U',
  1313. 'ext': 'mp4',
  1314. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  1315. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  1316. 'duration': 433,
  1317. 'upload_date': '20130923',
  1318. 'uploader': 'Amelia Putri Harwita',
  1319. 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
  1320. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
  1321. 'formats': 'maxcount:10',
  1322. },
  1323. 'params': {
  1324. 'skip_download': True,
  1325. 'youtube_include_dash_manifest': False,
  1326. },
  1327. 'skip': 'not actual any more',
  1328. },
  1329. {
  1330. # Youtube Music Auto-generated description
  1331. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  1332. 'info_dict': {
  1333. 'id': 'MgNrAu2pzNs',
  1334. 'ext': 'mp4',
  1335. 'title': 'Voyeur Girl',
  1336. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  1337. 'upload_date': '20190312',
  1338. 'uploader': 'Stephen - Topic',
  1339. 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
  1340. 'artist': 'Stephen',
  1341. 'track': 'Voyeur Girl',
  1342. 'album': 'it\'s too much love to know my dear',
  1343. 'release_date': '20190313',
  1344. 'release_year': 2019,
  1345. },
  1346. 'params': {
  1347. 'skip_download': True,
  1348. },
  1349. },
  1350. {
  1351. 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
  1352. 'only_matching': True,
  1353. },
  1354. {
  1355. # invalid -> valid video id redirection
  1356. 'url': 'DJztXj2GPfl',
  1357. 'info_dict': {
  1358. 'id': 'DJztXj2GPfk',
  1359. 'ext': 'mp4',
  1360. 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
  1361. 'description': 'md5:bf577a41da97918e94fa9798d9228825',
  1362. 'upload_date': '20090125',
  1363. 'uploader': 'Prochorowka',
  1364. 'uploader_id': 'Prochorowka',
  1365. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
  1366. 'artist': 'Panjabi MC',
  1367. 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
  1368. 'album': 'Beware of the Boys (Mundian To Bach Ke)',
  1369. },
  1370. 'params': {
  1371. 'skip_download': True,
  1372. },
  1373. 'skip': 'Video unavailable',
  1374. },
  1375. {
  1376. # empty description results in an empty string
  1377. 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
  1378. 'info_dict': {
  1379. 'id': 'x41yOUIvK2k',
  1380. 'ext': 'mp4',
  1381. 'title': 'IMG 3456',
  1382. 'description': '',
  1383. 'upload_date': '20170613',
  1384. 'uploader': "l'Or Vert asbl",
  1385. 'uploader_id': '@ElevageOrVert',
  1386. },
  1387. 'params': {
  1388. 'skip_download': True,
  1389. },
  1390. },
  1391. {
  1392. # with '};' inside yt initial data (see [1])
  1393. # see [2] for an example with '};' inside ytInitialPlayerResponse
  1394. # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
  1395. # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
  1396. 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
  1397. 'info_dict': {
  1398. 'id': 'CHqg6qOn4no',
  1399. 'ext': 'mp4',
  1400. 'title': 'Part 77 Sort a list of simple types in c#',
  1401. 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
  1402. 'upload_date': '20130831',
  1403. 'uploader': 'kudvenkat',
  1404. 'uploader_id': '@Csharp-video-tutorialsBlogspot',
  1405. },
  1406. 'params': {
  1407. 'skip_download': True,
  1408. },
  1409. },
  1410. {
  1411. # another example of '};' in ytInitialData
  1412. 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
  1413. 'only_matching': True,
  1414. },
  1415. {
  1416. 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
  1417. 'only_matching': True,
  1418. },
  1419. {
  1420. # https://github.com/ytdl-org/youtube-dl/pull/28094
  1421. 'url': 'OtqTfy26tG0',
  1422. 'info_dict': {
  1423. 'id': 'OtqTfy26tG0',
  1424. 'ext': 'mp4',
  1425. 'title': 'Burn Out',
  1426. 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
  1427. 'upload_date': '20141120',
  1428. 'uploader': 'The Cinematic Orchestra - Topic',
  1429. 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
  1430. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
  1431. 'artist': 'The Cinematic Orchestra',
  1432. 'track': 'Burn Out',
  1433. 'album': 'Every Day',
  1434. 'release_data': None,
  1435. 'release_year': None,
  1436. },
  1437. 'params': {
  1438. 'skip_download': True,
  1439. },
  1440. },
  1441. {
  1442. # controversial video, only works with bpctr when authenticated with cookies
  1443. 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
  1444. 'only_matching': True,
  1445. },
  1446. {
  1447. # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
  1448. 'url': 'cBvYw8_A0vQ',
  1449. 'info_dict': {
  1450. 'id': 'cBvYw8_A0vQ',
  1451. 'ext': 'mp4',
  1452. 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
  1453. 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
  1454. 'upload_date': '20201120',
  1455. 'uploader': 'Walk around Japan',
  1456. 'uploader_id': '@walkaroundjapan7124',
  1457. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@walkaroundjapan7124',
  1458. },
  1459. 'params': {
  1460. 'skip_download': True,
  1461. },
  1462. },
  1463. {
  1464. # YT 'Shorts'
  1465. 'url': 'https://youtube.com/shorts/4L2J27mJ3Dc',
  1466. 'info_dict': {
  1467. 'id': '4L2J27mJ3Dc',
  1468. 'ext': 'mp4',
  1469. 'title': 'Midwest Squid Game #Shorts',
  1470. 'description': 'md5:976512b8a29269b93bbd8a61edc45a6d',
  1471. 'upload_date': '20211025',
  1472. 'uploader': 'Charlie Berens',
  1473. 'uploader_id': '@CharlieBerens',
  1474. },
  1475. 'params': {
  1476. 'skip_download': True,
  1477. },
  1478. },
  1479. ]
  1480. _formats = {
  1481. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1482. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1483. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  1484. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  1485. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  1486. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1487. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1488. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1489. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  1490. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  1491. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1492. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1493. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1494. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1495. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1496. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1497. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1498. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1499. # 3D videos
  1500. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1501. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1502. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1503. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1504. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  1505. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1506. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1507. # Apple HTTP Live Streaming
  1508. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1509. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1510. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1511. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1512. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1513. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1514. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1515. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  1516. # DASH mp4 video
  1517. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1518. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1519. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1520. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1521. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1522. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  1523. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1524. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1525. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1526. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1527. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1528. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1529. # Dash mp4 audio
  1530. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  1531. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  1532. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  1533. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1534. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1535. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  1536. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  1537. # Dash webm
  1538. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1539. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1540. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1541. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1542. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1543. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1544. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  1545. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1546. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1547. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1548. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1549. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1550. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1551. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1552. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1553. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  1554. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1555. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1556. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1557. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1558. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1559. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1560. # Dash webm audio
  1561. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  1562. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  1563. # Dash webm audio with opus inside
  1564. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  1565. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  1566. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  1567. # RTMP (unnamed)
  1568. '_rtmp': {'protocol': 'rtmp'},
  1569. # av01 video only formats sometimes served with "unknown" codecs
  1570. '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1571. '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1572. '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1573. '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1574. }
  1575. _PLAYER_JS_VARIANT_MAP = (
  1576. ('main', 'player_ias.vflset/en_US/base.js'),
  1577. ('tcc', 'player_ias_tcc.vflset/en_US/base.js'),
  1578. ('tce', 'player_ias_tce.vflset/en_US/base.js'),
  1579. ('es5', 'player_es5.vflset/en_US/base.js'),
  1580. ('es6', 'player_es6.vflset/en_US/base.js'),
  1581. ('tv', 'tv-player-ias.vflset/tv-player-ias.js'),
  1582. ('tv_es6', 'tv-player-es6.vflset/tv-player-es6.js'),
  1583. ('phone', 'player-plasma-ias-phone-en_US.vflset/base.js'),
  1584. ('tablet', 'player-plasma-ias-tablet-en_US.vflset/base.js'),
  1585. )
  1586. @classmethod
  1587. def suitable(cls, url):
  1588. if parse_qs(url).get('list', [None])[0]:
  1589. return False
  1590. return super(YoutubeIE, cls).suitable(url)
  1591. def __init__(self, *args, **kwargs):
  1592. super(YoutubeIE, self).__init__(*args, **kwargs)
  1593. self._code_cache = {}
  1594. self._player_cache = {}
  1595. def _get_player_js_version(self):
  1596. player_js_version = self.get_param('youtube_player_js_version') or '20348@0004de42'
  1597. sts_hash = self._search_regex(
  1598. ('^actual$(^)?(^)?', r'^([0-9]{5,})@([0-9a-f]{8,})$'),
  1599. player_js_version, 'player_js_version', group=(1, 2), default=None)
  1600. if sts_hash:
  1601. return sts_hash
  1602. self.report_warning(
  1603. 'Invalid player JS version "{0}" specified. '
  1604. 'It should be "{1}" or in the format of {2}'.format(
  1605. player_js_version, 'actual', 'SignatureTimeStamp@Hash'), only_once=True)
  1606. return None, None
  1607. # *ytcfgs, webpage=None
  1608. def _extract_player_url(self, *ytcfgs, **kw_webpage):
  1609. if ytcfgs and not isinstance(ytcfgs[0], dict):
  1610. webpage = kw_webpage.get('webpage') or ytcfgs[0]
  1611. if webpage:
  1612. player_url = self._search_regex(
  1613. r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
  1614. webpage or '', 'player URL', fatal=False)
  1615. if player_url:
  1616. ytcfgs = ytcfgs + ({'PLAYER_JS_URL': player_url},)
  1617. player_url = traverse_obj(
  1618. ytcfgs, (Ellipsis, 'PLAYER_JS_URL'), (Ellipsis, 'WEB_PLAYER_CONTEXT_CONFIGS', Ellipsis, 'jsUrl'),
  1619. get_all=False, expected_type=lambda u: urljoin('https://www.youtube.com', u))
  1620. player_id_override = self._get_player_js_version()[1]
  1621. requested_js_variant = self.get_param('youtube_player_js_variant') or 'main'
  1622. variant_js = next(
  1623. (v for k, v in self._PLAYER_JS_VARIANT_MAP if k == requested_js_variant),
  1624. None)
  1625. if variant_js:
  1626. player_id = player_id_override or self._extract_player_info(player_url)
  1627. original_url = player_url
  1628. player_url = '/s/player/{0}/{1}'.format(player_id, variant_js)
  1629. if original_url != player_url:
  1630. self.write_debug(
  1631. 'Forcing "{0}" player JS variant for player {1}\n'
  1632. ' original url = {2}'.format(
  1633. requested_js_variant, player_id, original_url),
  1634. only_once=True)
  1635. elif requested_js_variant != 'actual':
  1636. self.report_warning(
  1637. 'Invalid player JS variant name "{0}" requested. '
  1638. 'Valid choices are: {1}'.format(
  1639. requested_js_variant, ','.join(k for k, _ in self._PLAYER_JS_VARIANT_MAP)),
  1640. only_once=True)
  1641. return urljoin('https://www.youtube.com', player_url)
  1642. def _download_player_url(self, video_id, fatal=False):
  1643. res = self._download_webpage(
  1644. 'https://www.youtube.com/iframe_api',
  1645. note='Downloading iframe API JS', video_id=video_id, fatal=fatal)
  1646. player_version = self._search_regex(
  1647. r'player\\?/([0-9a-fA-F]{8})\\?/', res or '', 'player version', fatal=fatal,
  1648. default=NO_DEFAULT if res else None) or None
  1649. return player_version and 'https://www.youtube.com/s/player/{0}/player_ias.vflset/en_US/base.js'.format(player_version)
  1650. def _signature_cache_id(self, example_sig):
  1651. """ Return a string representation of a signature """
  1652. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  1653. def _extract_player_info(self, player_url):
  1654. try:
  1655. return self._search_regex(
  1656. self._PLAYER_INFO_RE, player_url, 'player info', group='id')
  1657. except ExtractorError as e:
  1658. raise ExtractorError(
  1659. 'Cannot identify player %r' % (player_url,), cause=e)
  1660. def _player_js_cache_key(self, player_url, extra_id=None, _cache={}):
  1661. if player_url not in _cache:
  1662. player_id = self._extract_player_info(player_url)
  1663. player_path = remove_start(
  1664. compat_urllib_parse.urlparse(player_url).path,
  1665. '/s/player/{0}/'.format(player_id))
  1666. variant = next((k for k, v in self._PLAYER_JS_VARIANT_MAP
  1667. if v == player_path), None)
  1668. if not variant:
  1669. variant = next(
  1670. (k for k, v in self._PLAYER_JS_VARIANT_MAP
  1671. if re.match(re.escape(v).replace('en_US', r'\w+') + '$', player_path)),
  1672. None)
  1673. if not variant:
  1674. self.write_debug(
  1675. 'Unable to determine player JS variant\n'
  1676. ' player = {0}'.format(player_url), only_once=True)
  1677. variant = re.sub(r'[^a-zA-Z0-9]', '_', remove_end(player_path, '.js'))
  1678. _cache[player_url] = join_nonempty(player_id, variant)
  1679. if extra_id:
  1680. extra_id = '-'.join((_cache[player_url], extra_id))
  1681. assert os.path.basename(extra_id) == extra_id
  1682. return extra_id
  1683. return _cache[player_url]
  1684. def _load_player(self, video_id, player_url, fatal=True):
  1685. player_js_key = self._player_js_cache_key(player_url)
  1686. if player_js_key not in self._code_cache:
  1687. code = self._download_webpage(
  1688. player_url, video_id, fatal=fatal,
  1689. note='Downloading player {0}'.format(player_js_key),
  1690. errnote='Download of {0} failed'.format(player_url))
  1691. if code:
  1692. self._code_cache[player_js_key] = code
  1693. return self._code_cache.get(player_js_key)
  1694. def _load_player_data_from_cache(self, name, player_url, extra_id=None):
  1695. cache_id = ('youtube-{0}'.format(name), self._player_js_cache_key(player_url, extra_id))
  1696. data = self._player_cache.get(cache_id)
  1697. if data:
  1698. return data
  1699. data = self.cache.load(*cache_id, min_ver='2025.04.07')
  1700. if data:
  1701. self._player_cache[cache_id] = data
  1702. return data
  1703. def _store_player_data_to_cache(self, name, player_url, data, extra_id=None):
  1704. cache_id = ('youtube-{0}'.format(name), self._player_js_cache_key(player_url, extra_id))
  1705. if cache_id not in self._player_cache:
  1706. self.cache.store(cache_id[0], cache_id[1], data)
  1707. self._player_cache[cache_id] = data
  1708. def _remove_player_data_from_cache(self, name, player_url, extra_id=None):
  1709. cache_id = ('youtube-{0}'.format(name), self._player_js_cache_key(player_url, extra_id))
  1710. if cache_id in self._player_cache:
  1711. self.cache.clear(*cache_id)
  1712. self._player_cache.pop(cache_id, None)
  1713. def _extract_signature_function(self, video_id, player_url, example_sig):
  1714. # player_id = self._extract_player_info(player_url)
  1715. # Read from filesystem cache
  1716. extra_id = self._signature_cache_id(example_sig)
  1717. self.write_debug('Extracting signature function {0}-{1}'.format(player_url, extra_id))
  1718. cache_spec, code = self._load_player_data_from_cache(
  1719. 'sigfuncs', player_url, extra_id=extra_id), None
  1720. if not cache_spec:
  1721. code = self._load_player(video_id, player_url)
  1722. if code:
  1723. res = self._parse_sig_js(code)
  1724. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1725. cache_spec = [ord(c) for c in res(test_string)]
  1726. self._store_player_data_to_cache(
  1727. 'sigfuncs', player_url, cache_spec, extra_id=extra_id)
  1728. else:
  1729. self.report_warning(
  1730. 'Failed to compute signature function {0}-{1}'.format(
  1731. player_url, extra_id))
  1732. return lambda s: ''.join(s[i] for i in cache_spec)
  1733. def _print_sig_code(self, func, example_sig):
  1734. if not self.get_param('youtube_print_sig_code'):
  1735. return
  1736. def gen_sig_code(idxs):
  1737. def _genslice(start, end, step):
  1738. starts = '' if start == 0 else str(start)
  1739. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  1740. steps = '' if step == 1 else (':%d' % step)
  1741. return 's[{0}{1}{2}]'.format(starts, ends, steps)
  1742. step = None
  1743. # Quelch pyflakes warnings - start will be set when step is set
  1744. start = '(Never used)'
  1745. for i, prev in zip(idxs[1:], idxs[:-1]):
  1746. if step is not None:
  1747. if i - prev == step:
  1748. continue
  1749. yield _genslice(start, prev, step)
  1750. step = None
  1751. continue
  1752. if i - prev in [-1, 1]:
  1753. step = i - prev
  1754. start = prev
  1755. continue
  1756. else:
  1757. yield 's[%d]' % prev
  1758. if step is None:
  1759. yield 's[%d]' % i
  1760. else:
  1761. yield _genslice(start, i, step)
  1762. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1763. cache_res = func(test_string)
  1764. cache_spec = [ord(c) for c in cache_res]
  1765. expr_code = ' + '.join(gen_sig_code(cache_spec))
  1766. signature_id_tuple = '(%s)' % (
  1767. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  1768. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  1769. ' return %s\n') % (signature_id_tuple, expr_code)
  1770. self.to_screen('Extracted signature function:\n' + code)
  1771. def _extract_sig_fn(self, jsi, funcname):
  1772. var_ay = self._search_regex(
  1773. r'''(?x)
  1774. (?:\*/|\{|\n|^)\s*(?:'[^']+'\s*;\s*)
  1775. (var\s*[\w$]+\s*=\s*(?:
  1776. ('|")(?:\\\2|(?!\2).)+\2\s*\.\s*split\(\s*('|")\W+\3\s*\)|
  1777. \[\s*(?:('|")(?:\\\4|(?!\4).)*\4\s*(?:(?=\])|,\s*))+\]
  1778. ))(?=\s*[,;])
  1779. ''', jsi.code, 'useful values', default='')
  1780. sig_fn = jsi.extract_function_code(funcname)
  1781. if var_ay:
  1782. sig_fn = (sig_fn[0], ';\n'.join((var_ay, sig_fn[1])))
  1783. return sig_fn
  1784. def _parse_sig_js(self, jscode):
  1785. # Examples where `sig` is funcname:
  1786. # sig=function(a){a=a.split(""); ... ;return a.join("")};
  1787. # ;c&&(c=sig(decodeURIComponent(c)),a.set(b,encodeURIComponent(c)));return a};
  1788. # {var l=f,m=h.sp,n=sig(decodeURIComponent(h.s));l.set(m,encodeURIComponent(n))}
  1789. # sig=function(J){J=J.split(""); ... ;return J.join("")};
  1790. # ;N&&(N=sig(decodeURIComponent(N)),J.set(R,encodeURIComponent(N)));return J};
  1791. # {var H=u,k=f.sp,v=sig(decodeURIComponent(f.s));H.set(k,encodeURIComponent(v))}
  1792. funcname = self._search_regex(
  1793. (r'\b(?P<var>[\w$]+)&&\((?P=var)=(?P<sig>[\w$]{2,})\(decodeURIComponent\((?P=var)\)\)',
  1794. r'(?P<sig>[\w$]+)\s*=\s*function\(\s*(?P<arg>[\w$]+)\s*\)\s*{\s*(?P=arg)\s*=\s*(?P=arg)\.split\(\s*""\s*\)\s*;\s*[^}]+;\s*return\s+(?P=arg)\.join\(\s*""\s*\)',
  1795. r'(?:\b|[^\w$])(?P<sig>[\w$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)(?:;[\w$]{2}\.[\w$]{2}\(a,\d+\))?',
  1796. # Old patterns
  1797. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[\w$]+)\(',
  1798. r'\b[\w]+\s*&&\s*[\w]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[\w$]+)\(',
  1799. r'\bm=(?P<sig>[\w$]{2,})\(decodeURIComponent\(h\.s\)\)',
  1800. # Obsolete patterns
  1801. r'("|\')signature\1\s*,\s*(?P<sig>[\w$]+)\(',
  1802. r'\.sig\|\|(?P<sig>[\w$]+)\(',
  1803. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[\w$]+)\(',
  1804. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[\w$]+)\(',
  1805. r'\bc\s*&&\s*[\w]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[\w$]+)\('),
  1806. jscode, 'Initial JS player signature function name', group='sig')
  1807. jsi = JSInterpreter(jscode)
  1808. initial_function = self._extract_sig_fn(jsi, funcname)
  1809. func = jsi.extract_function_from_code(*initial_function)
  1810. return lambda s: func([s])
  1811. def _cached(self, func, *cache_id):
  1812. def inner(*args, **kwargs):
  1813. if cache_id not in self._player_cache:
  1814. try:
  1815. self._player_cache[cache_id] = func(*args, **kwargs)
  1816. except ExtractorError as e:
  1817. self._player_cache[cache_id] = e
  1818. except Exception as e:
  1819. self._player_cache[cache_id] = ExtractorError(traceback.format_exc(), cause=e)
  1820. ret = self._player_cache[cache_id]
  1821. if isinstance(ret, Exception):
  1822. raise ret
  1823. return ret
  1824. return inner
  1825. def _decrypt_signature(self, s, video_id, player_url):
  1826. """Turn the encrypted s field into a working signature"""
  1827. extract_sig = self._cached(
  1828. self._extract_signature_function, 'sig', player_url, self._signature_cache_id(s))
  1829. func = extract_sig(video_id, player_url, s)
  1830. self._print_sig_code(func, s)
  1831. return func(s)
  1832. # from yt-dlp
  1833. # See also:
  1834. # 1. https://github.com/ytdl-org/youtube-dl/issues/29326#issuecomment-894619419
  1835. # 2. https://code.videolan.org/videolan/vlc/-/blob/4fb284e5af69aa9ac2100ccbdd3b88debec9987f/share/lua/playlist/youtube.lua#L116
  1836. # 3. https://github.com/ytdl-org/youtube-dl/issues/30097#issuecomment-950157377
  1837. def _decrypt_nsig(self, n, video_id, player_url):
  1838. """Turn the encrypted n field into a working signature"""
  1839. if player_url is None:
  1840. raise ExtractorError('Cannot decrypt nsig without player_url')
  1841. try:
  1842. jsi, player_id, func_code = self._extract_n_function_code(video_id, player_url)
  1843. except ExtractorError as e:
  1844. raise ExtractorError('Unable to extract nsig function code', cause=e)
  1845. if self.get_param('youtube_print_sig_code'):
  1846. self.to_screen('Extracted nsig function from {0}:\n{1}\n'.format(
  1847. player_id, func_code[1]))
  1848. try:
  1849. extract_nsig = self._cached(self._extract_n_function_from_code, 'nsig func', player_url)
  1850. ret = extract_nsig(jsi, func_code)(n)
  1851. except JSInterpreter.Exception as e:
  1852. self.report_warning(
  1853. '%s (%s %s)' % (
  1854. 'Unable to decode n-parameter: expect download to be blocked or throttled',
  1855. error_to_compat_str(e),
  1856. traceback.format_exc()),
  1857. video_id=video_id)
  1858. return
  1859. self.write_debug('Decrypted nsig {0} => {1}'.format(n, ret))
  1860. return ret
  1861. def _extract_n_function_name(self, jscode):
  1862. func_name, idx = None, None
  1863. def generic_n_function_search(func_name=None):
  1864. return self._search_regex(
  1865. r'''(?xs)
  1866. (?:(?<=[^\w$])|^) # instead of \b, which ignores $
  1867. (?P<name>%s)\s*=\s*function\((?!\d)[a-zA-Z\d_$]+\)
  1868. \s*\{(?:(?!};).)+?(?:
  1869. ["']enhanced_except_ |
  1870. return\s*(?P<q>"|')[a-zA-Z\d-]+_w8_(?P=q)\s*\+\s*[\w$]+
  1871. )
  1872. ''' % (func_name or r'(?!\d)[a-zA-Z\d_$]+',), jscode,
  1873. 'Initial JS player n function name', group='name',
  1874. default=None if func_name else NO_DEFAULT)
  1875. # these special cases are redundant and probably obsolete (2025-04):
  1876. # they make the tests run ~10% faster without fallback warnings
  1877. r"""
  1878. func_name, idx = self._search_regex(
  1879. # (y=NuD(),Mw(k),q=k.Z[y]||null)&&(q=narray[idx](q),k.set(y,q),k.V||NuD(''))}};
  1880. # (R="nn"[+J.Z],mW(J),N=J.K[R]||null)&&(N=narray[idx](N),J.set(R,N))}};
  1881. # or: (b=String.fromCharCode(110),c=a.get(b))&&c=narray[idx](c)
  1882. # or: (b="nn"[+a.D],c=a.get(b))&&(c=narray[idx](c)
  1883. # or: (PL(a),b=a.j.n||null)&&(b=narray[idx](b)
  1884. # or: (b="nn"[+a.D],vL(a),c=a.j[b]||null)&&(c=narray[idx](c),a.set(b,c),narray.length||nfunc("")
  1885. # old: (b=a.get("n"))&&(b=narray[idx](b)(?P<c>[a-z])\s*=\s*[a-z]\s*
  1886. # older: (b=a.get("n"))&&(b=nfunc(b)
  1887. r'''(?x)
  1888. # (expr, ...,
  1889. \((?:(?:\s*[\w$]+\s*=)?(?:[\w$"+\.\s(\[]+(?:[)\]]\s*)?),)*
  1890. # b=...
  1891. (?P<b>[\w$]+)\s*=\s*(?!(?P=b)[^\w$])[\w$]+\s*(?:(?:
  1892. \.\s*[\w$]+ |
  1893. \[\s*[\w$]+\s*\] |
  1894. \.\s*get\s*\(\s*[\w$"]+\s*\)
  1895. )\s*){,2}(?:\s*\|\|\s*null(?=\s*\)))?\s*
  1896. \)\s*&&\s*\( # ...)&&(
  1897. # b = nfunc, b = narray[idx]
  1898. (?P=b)\s*=\s*(?P<nfunc>[\w$]+)\s*
  1899. (?:\[\s*(?P<idx>[\w$]+)\s*\]\s*)?
  1900. # (...)
  1901. \(\s*[\w$]+\s*\)
  1902. ''', jscode, 'Initial JS player n function name', group=('nfunc', 'idx'),
  1903. default=(None, None))
  1904. """
  1905. if not func_name:
  1906. # nfunc=function(x){...}|function nfunc(x); ...
  1907. # ... var y=[nfunc]|y[idx]=nfunc);
  1908. # obvious REs hang, so use a two-stage tactic
  1909. for m in re.finditer(r'''(?x)
  1910. [\n;]var\s(?:(?:(?!,).)+,|\s)*?(?!\d)[\w$]+(?:\[(?P<idx>\d+)\])?\s*=\s*
  1911. (?(idx)|\[\s*)(?P<nfunc>(?!\d)[\w$]+)(?(idx)|\s*\])
  1912. \s*?[;\n]
  1913. ''', jscode):
  1914. fn = self._search_regex(
  1915. r'[;,]\s*(function\s+)?({0})(?(1)|\s*=\s*function)\s*\((?!\d)[\w$]+\)\s*\{1}(?!\s*return\s)'.format(
  1916. re.escape(m.group('nfunc')), '{'),
  1917. jscode, 'Initial JS player n function name (2)', group=2, default=None)
  1918. if fn:
  1919. func_name = fn
  1920. idx = m.group('idx')
  1921. if generic_n_function_search(func_name):
  1922. # don't look any further
  1923. break
  1924. # thx bashonly: yt-dlp/yt-dlp/pull/10611
  1925. if not func_name:
  1926. self.report_warning('Falling back to generic n function search', only_once=True)
  1927. return generic_n_function_search()
  1928. if not idx:
  1929. return func_name
  1930. return self._search_json(
  1931. r'(?<![\w-])var\s(?:(?:(?!,).)+,|\s)*?{0}\s*='.format(re.escape(func_name)), jscode,
  1932. 'Initial JS player n function list ({0}.{1})'.format(func_name, idx),
  1933. func_name, contains_pattern=r'\[.+\]', end_pattern='[,;]',
  1934. transform_source=js_to_json)[int(idx)]
  1935. def _extract_n_function_code(self, video_id, player_url):
  1936. player_id = self._extract_player_info(player_url)
  1937. func_code = self._load_player_data_from_cache('nsig', player_url)
  1938. jscode = func_code or self._load_player(video_id, player_url)
  1939. jsi = JSInterpreter(jscode)
  1940. if func_code:
  1941. return jsi, player_id, func_code
  1942. return self._extract_n_function_code_jsi(video_id, jsi, player_id, player_url)
  1943. def _extract_n_function_code_jsi(self, video_id, jsi, player_id=None, player_url=None):
  1944. func_name = self._extract_n_function_name(jsi.code)
  1945. func_code = self._extract_sig_fn(jsi, func_name)
  1946. if player_url:
  1947. self._store_player_data_to_cache('nsig', player_url, func_code)
  1948. return jsi, player_id, func_code
  1949. def _extract_n_function_from_code(self, jsi, func_code):
  1950. func = jsi.extract_function_from_code(*func_code)
  1951. def extract_nsig(s):
  1952. try:
  1953. ret = func([s], kwargs={'_ytdl_do_not_return': s})
  1954. except JSInterpreter.Exception:
  1955. raise
  1956. except Exception as e:
  1957. raise JSInterpreter.Exception(traceback.format_exc(), cause=e)
  1958. if ret.startswith('enhanced_except_') or ret.endswith(s):
  1959. raise JSInterpreter.Exception('Signature function returned an exception')
  1960. return ret
  1961. return extract_nsig
  1962. def _unthrottle_format_urls(self, video_id, player_url, *formats):
  1963. def decrypt_nsig(n):
  1964. return self._cached(self._decrypt_nsig, 'nsig', n, player_url)
  1965. for fmt in formats:
  1966. n_param = parse_qs(fmt['url']).get('n')
  1967. if not n_param:
  1968. continue
  1969. n_param = n_param[-1]
  1970. n_response = decrypt_nsig(n_param)(n_param, video_id, player_url)
  1971. if n_response is None:
  1972. # give up and forget cached data if descrambling failed
  1973. self._remove_player_data_from_cache('nsig', player_url)
  1974. break
  1975. fmt['url'] = update_url_query(fmt['url'], {'n': n_response})
  1976. # from yt-dlp, with tweaks
  1977. def _extract_signature_timestamp(self, video_id, player_url, ytcfg=None, fatal=False):
  1978. """
  1979. Extract signatureTimestamp (sts)
  1980. Required to tell API what sig/player version is in use.
  1981. """
  1982. sts = traverse_obj(
  1983. (self._get_player_js_version(), ytcfg),
  1984. (0, 0),
  1985. (1, 'STS'),
  1986. expected_type=int_or_none)
  1987. if sts:
  1988. return sts
  1989. if not player_url:
  1990. error_msg = 'Cannot extract signature timestamp without player url'
  1991. if fatal:
  1992. raise ExtractorError(error_msg)
  1993. self.report_warning(error_msg)
  1994. return None
  1995. sts = self._load_player_data_from_cache('sts', player_url)
  1996. if sts:
  1997. return sts
  1998. # Attempt to extract from player
  1999. code = self._load_player(video_id, player_url, fatal=fatal)
  2000. sts = int_or_none(self._search_regex(
  2001. r'(?:signatureTimestamp|sts)\s*:\s*(?P<sts>[0-9]{5})', code or '',
  2002. 'JS player signature timestamp', group='sts', fatal=fatal))
  2003. if sts:
  2004. self._store_player_data_to_cache('sts', player_url, sts)
  2005. return sts
  2006. def _mark_watched(self, video_id, player_response):
  2007. playback_url = url_or_none(try_get(
  2008. player_response,
  2009. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']))
  2010. if not playback_url:
  2011. return
  2012. # cpn generation algorithm is reverse engineered from base.js.
  2013. # In fact it works even with dummy cpn.
  2014. CPN_ALPHABET = string.ascii_letters + string.digits + '-_'
  2015. cpn = ''.join(CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(16))
  2016. # more consistent results setting it to right before the end
  2017. qs = parse_qs(playback_url)
  2018. video_length = '{0}'.format(float((qs.get('len') or ['1.5'])[0]) - 1)
  2019. playback_url = update_url_query(
  2020. playback_url, {
  2021. 'ver': '2',
  2022. 'cpn': cpn,
  2023. 'cmt': video_length,
  2024. 'el': 'detailpage', # otherwise defaults to "shorts"
  2025. })
  2026. self._download_webpage(
  2027. playback_url, video_id, 'Marking watched',
  2028. 'Unable to mark watched', fatal=False)
  2029. @staticmethod
  2030. def _extract_urls(webpage):
  2031. # Embedded YouTube player
  2032. entries = [
  2033. unescapeHTML(mobj.group('url'))
  2034. for mobj in re.finditer(r'''(?x)
  2035. (?:
  2036. <iframe[^>]+?src=|
  2037. data-video-url=|
  2038. <embed[^>]+?src=|
  2039. embedSWF\(?:\s*|
  2040. <object[^>]+data=|
  2041. new\s+SWFObject\(
  2042. )
  2043. (["\'])
  2044. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  2045. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  2046. \1''', webpage)]
  2047. # lazyYT YouTube embed
  2048. entries.extend(list(map(
  2049. unescapeHTML,
  2050. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  2051. # Wordpress "YouTube Video Importer" plugin
  2052. matches = re.findall(r'''(?x)<div[^>]+
  2053. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  2054. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  2055. entries.extend(m[-1] for m in matches)
  2056. return entries
  2057. @staticmethod
  2058. def _extract_url(webpage):
  2059. urls = YoutubeIE._extract_urls(webpage)
  2060. return urls[0] if urls else None
  2061. @classmethod
  2062. def extract_id(cls, url):
  2063. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  2064. if mobj is None:
  2065. raise ExtractorError('Invalid URL: %s' % url)
  2066. return mobj.group(2)
  2067. @staticmethod
  2068. def _extract_chapters_from_json(data, video_id, duration):
  2069. chapters_list = try_get(
  2070. data,
  2071. lambda x: x['playerOverlays']
  2072. ['playerOverlayRenderer']
  2073. ['decoratedPlayerBarRenderer']
  2074. ['decoratedPlayerBarRenderer']
  2075. ['playerBar']
  2076. ['chapteredPlayerBarRenderer']
  2077. ['chapters'],
  2078. list)
  2079. if not chapters_list:
  2080. return
  2081. def chapter_time(chapter):
  2082. return float_or_none(
  2083. try_get(
  2084. chapter,
  2085. lambda x: x['chapterRenderer']['timeRangeStartMillis'],
  2086. int),
  2087. scale=1000)
  2088. chapters = []
  2089. for next_num, chapter in enumerate(chapters_list, start=1):
  2090. start_time = chapter_time(chapter)
  2091. if start_time is None:
  2092. continue
  2093. end_time = (chapter_time(chapters_list[next_num])
  2094. if next_num < len(chapters_list) else duration)
  2095. if end_time is None:
  2096. continue
  2097. title = try_get(
  2098. chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
  2099. compat_str)
  2100. chapters.append({
  2101. 'start_time': start_time,
  2102. 'end_time': end_time,
  2103. 'title': title,
  2104. })
  2105. return chapters
  2106. def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
  2107. return self._parse_json(self._search_regex(
  2108. (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
  2109. regex), webpage, name, default='{}'), video_id, fatal=False)
  2110. def _get_preroll_length(self, ad_slot_lists):
  2111. def parse_instream_ad_renderer(instream_renderer):
  2112. for skippable, path in (
  2113. ('', ('skipOffsetMilliseconds', T(int))),
  2114. ('non-', ('playerVars', T(compat_parse_qs),
  2115. 'length_seconds', -1, T(int_or_none(invscale=1000))))):
  2116. length_ms = traverse_obj(instream_renderer, path)
  2117. if length_ms is not None:
  2118. self.write_debug('Detected a %ds %sskippable ad' % (
  2119. length_ms // 1000, skippable))
  2120. break
  2121. return length_ms
  2122. for slot_renderer in traverse_obj(ad_slot_lists, ('adSlots', Ellipsis, 'adSlotRenderer', T(dict))):
  2123. if traverse_obj(slot_renderer, ('adSlotMetadata', 'triggerEvent')) != 'SLOT_TRIGGER_EVENT_BEFORE_CONTENT':
  2124. continue
  2125. rendering_content = traverse_obj(slot_renderer, (
  2126. 'fulfillmentContent', 'fulfilledLayout', 'playerBytesAdLayoutRenderer',
  2127. 'renderingContent', 'instreamVideoAdRenderer', T(dict)))
  2128. length_ms = parse_instream_ad_renderer(rendering_content)
  2129. if length_ms is not None:
  2130. return length_ms
  2131. times = traverse_obj(rendering_content, ((
  2132. ('playerBytesSequentialLayoutRenderer', 'sequentialLayouts'),
  2133. None), any, Ellipsis, 'playerBytesAdLayoutRenderer',
  2134. 'renderingContent', 'instreamVideoAdRenderer',
  2135. T(parse_instream_ad_renderer)))
  2136. if times:
  2137. return sum(times)
  2138. return 0
  2139. def _is_premium_subscriber(self, initial_data):
  2140. if not self.is_authenticated or not initial_data:
  2141. return False
  2142. tlr = traverse_obj(
  2143. initial_data, ('topbar', 'desktopTopbarRenderer', 'logo', 'topbarLogoRenderer'))
  2144. return (
  2145. traverse_obj(tlr, ('iconImage', 'iconType')) == 'YOUTUBE_PREMIUM_LOGO'
  2146. or 'premium' in (self._get_text(tlr, 'tooltipText') or '').lower()
  2147. )
  2148. def _real_extract(self, url):
  2149. url, smuggled_data = unsmuggle_url(url, {})
  2150. video_id = self._match_id(url)
  2151. base_url = self.http_scheme() + '//www.youtube.com/'
  2152. webpage_url = base_url + 'watch?v=' + video_id
  2153. ua = traverse_obj(self._INNERTUBE_CLIENTS, (
  2154. 'web', 'INNERTUBE_CONTEXT', 'client', 'userAgent'))
  2155. headers = {'User-Agent': ua} if ua else None
  2156. webpage = self._download_webpage(
  2157. webpage_url + '&bpctr=9999999999&has_verified=1', video_id,
  2158. headers=headers, fatal=False)
  2159. player_response = None
  2160. player_url = None
  2161. if webpage:
  2162. player_response = self._extract_yt_initial_variable(
  2163. webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
  2164. video_id, 'initial player response')
  2165. is_live = traverse_obj(player_response, ('videoDetails', 'isLive'))
  2166. fetched_timestamp = None
  2167. if False and not player_response:
  2168. player_response = self._call_api(
  2169. 'player', {'videoId': video_id}, video_id)
  2170. if True or not player_response:
  2171. origin = 'https://www.youtube.com'
  2172. pb_context = {'html5Preference': 'HTML5_PREF_WANTS'}
  2173. player_url = self._extract_player_url(webpage)
  2174. ytcfg = self._extract_ytcfg(video_id, webpage or '')
  2175. sts = self._extract_signature_timestamp(video_id, player_url, ytcfg)
  2176. if sts:
  2177. pb_context['signatureTimestamp'] = sts
  2178. auth = self._generate_sapisidhash_header(origin)
  2179. client_names = []
  2180. if auth or self._is_premium_subscriber(player_response):
  2181. client_names = traverse_obj(self._INNERTUBE_CLIENTS, (
  2182. T(dict_items), lambda _, k_v: k_v[0] == 'web_safari', 0))[:1]
  2183. if not client_names:
  2184. client_names = traverse_obj(self._INNERTUBE_CLIENTS, (
  2185. T(dict_items), lambda _, k_v: not (
  2186. k_v[1].get('REQUIRE_PO_TOKEN')
  2187. or (bool(k_v[1].get('WITH_COOKIES', auth)) ^ bool(auth))
  2188. ), 0))[:1]
  2189. if 'web' not in client_names:
  2190. # only live HLS webpage links will download: ignore playability
  2191. player_response = filter_dict(
  2192. player_response or {},
  2193. lambda k, _: k != 'playabilityStatus')
  2194. headers = {
  2195. 'Sec-Fetch-Mode': 'navigate',
  2196. 'Origin': origin,
  2197. 'X-Goog-Visitor-Id': self._extract_visitor_data(ytcfg) or '',
  2198. }
  2199. if auth is not None:
  2200. headers['Authorization'] = auth
  2201. headers['X-Origin'] = origin
  2202. for client in traverse_obj(self._INNERTUBE_CLIENTS, (client_names, T(dict))):
  2203. query = {
  2204. 'playbackContext': {
  2205. 'contentPlaybackContext': pb_context,
  2206. },
  2207. 'contentCheckOk': True,
  2208. 'racyCheckOk': True,
  2209. 'context': {
  2210. 'client': merge_dicts(
  2211. traverse_obj(client, ('INNERTUBE_CONTEXT', 'client')), {
  2212. 'hl': 'en',
  2213. 'timeZone': 'UTC',
  2214. 'utcOffsetMinutes': 0,
  2215. }),
  2216. },
  2217. 'videoId': video_id,
  2218. }
  2219. api_headers = merge_dicts(headers, traverse_obj(client, {
  2220. 'X-YouTube-Client-Name': 'INNERTUBE_CONTEXT_CLIENT_NAME',
  2221. 'X-YouTube-Client-Version': (
  2222. 'INNERTUBE_CONTEXT', 'client', 'clientVersion'),
  2223. 'User-Agent': (
  2224. 'INNERTUBE_CONTEXT', 'client', 'userAgent'),
  2225. }) or {})
  2226. api_player_response = self._call_api(
  2227. 'player', query, video_id, fatal=False, headers=api_headers,
  2228. note=join_nonempty(
  2229. 'Downloading', traverse_obj(query, (
  2230. 'context', 'client', 'clientName')),
  2231. 'API JSON', delim=' '))
  2232. # be sure to find HLS in case of is_live
  2233. hls = traverse_obj(player_response, (
  2234. 'streamingData', 'hlsManifestUrl', T(url_or_none)))
  2235. fetched_timestamp = int(time.time())
  2236. preroll_length_ms = (
  2237. self._get_preroll_length(api_player_response)
  2238. or self._get_preroll_length(player_response))
  2239. video_details = merge_dicts(*traverse_obj(
  2240. (player_response, api_player_response),
  2241. (Ellipsis, 'videoDetails', T(dict))))
  2242. player_response.update(filter_dict(
  2243. api_player_response or {}, cndn=lambda k, _: k != 'captions'))
  2244. player_response['videoDetails'] = video_details
  2245. if hls and not traverse_obj(player_response, (
  2246. 'streamingData', 'hlsManifestUrl', T(url_or_none))):
  2247. player_response['streamingData']['hlsManifestUrl'] = hls
  2248. def is_agegated(playability):
  2249. # playability: dict
  2250. if not playability:
  2251. return False
  2252. if playability.get('desktopLegacyAgeGateReason'):
  2253. return True
  2254. reasons = traverse_obj(playability, (('status', 'reason'),))
  2255. AGE_GATE_REASONS = (
  2256. 'confirm your age', 'age-restricted', 'inappropriate', # reason
  2257. 'age_verification_required', 'age_check_required', # status
  2258. )
  2259. return any(expected in reason for expected in AGE_GATE_REASONS for reason in reasons)
  2260. def get_playability_status(response):
  2261. return try_get(response, lambda x: x['playabilityStatus'], dict) or {}
  2262. playability_status = get_playability_status(player_response)
  2263. if (is_agegated(playability_status)
  2264. and int_or_none(self._downloader.params.get('age_limit'), default=18) >= 18):
  2265. self.report_age_confirmation()
  2266. # Thanks: https://github.com/yt-dlp/yt-dlp/pull/3233
  2267. pb_context = {'html5Preference': 'HTML5_PREF_WANTS'}
  2268. # Use signatureTimestamp if available
  2269. # Thanks https://github.com/ytdl-org/youtube-dl/issues/31034#issuecomment-1160718026
  2270. player_url = self._extract_player_url(webpage)
  2271. ytcfg = self._extract_ytcfg(video_id, webpage)
  2272. sts = self._extract_signature_timestamp(video_id, player_url, ytcfg)
  2273. if sts:
  2274. pb_context['signatureTimestamp'] = sts
  2275. query = {
  2276. 'playbackContext': {'contentPlaybackContext': pb_context},
  2277. 'contentCheckOk': True,
  2278. 'racyCheckOk': True,
  2279. 'context': {
  2280. 'client': {'clientName': 'TVHTML5_SIMPLY_EMBEDDED_PLAYER', 'clientVersion': '2.0', 'hl': 'en', 'clientScreen': 'EMBED'},
  2281. 'thirdParty': {'embedUrl': 'https://google.com'},
  2282. },
  2283. 'videoId': video_id,
  2284. }
  2285. headers = {
  2286. 'X-YouTube-Client-Name': '85',
  2287. 'X-YouTube-Client-Version': '2.0',
  2288. 'Origin': 'https://www.youtube.com',
  2289. }
  2290. video_info = self._call_api('player', query, video_id, fatal=False, headers=headers)
  2291. age_gate_status = get_playability_status(video_info)
  2292. if age_gate_status.get('status') == 'OK':
  2293. player_response = video_info
  2294. playability_status = age_gate_status
  2295. trailer_video_id = try_get(
  2296. playability_status,
  2297. lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
  2298. compat_str)
  2299. if trailer_video_id:
  2300. return self.url_result(
  2301. trailer_video_id, self.ie_key(), trailer_video_id)
  2302. def get_text(x):
  2303. return ''.join(traverse_obj(
  2304. x, (('simpleText',),), ('runs', Ellipsis, 'text'),
  2305. expected_type=compat_str))
  2306. search_meta = (
  2307. (lambda x: self._html_search_meta(x, webpage, default=None))
  2308. if webpage else lambda _: None)
  2309. video_details = player_response.get('videoDetails') or {}
  2310. microformat = try_get(
  2311. player_response,
  2312. lambda x: x['microformat']['playerMicroformatRenderer'],
  2313. dict) or {}
  2314. video_title = video_details.get('title') \
  2315. or get_text(microformat.get('title')) \
  2316. or search_meta(['og:title', 'twitter:title', 'title'])
  2317. video_description = video_details.get('shortDescription')
  2318. if not smuggled_data.get('force_singlefeed', False):
  2319. if not self._downloader.params.get('noplaylist'):
  2320. multifeed_metadata_list = try_get(
  2321. player_response,
  2322. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  2323. compat_str)
  2324. if multifeed_metadata_list:
  2325. entries = []
  2326. feed_ids = []
  2327. for feed in multifeed_metadata_list.split(','):
  2328. # Unquote should take place before split on comma (,) since textual
  2329. # fields may contain comma as well (see
  2330. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  2331. feed_data = compat_parse_qs(
  2332. compat_urllib_parse_unquote_plus(feed))
  2333. def feed_entry(name):
  2334. return try_get(
  2335. feed_data, lambda x: x[name][0], compat_str)
  2336. feed_id = feed_entry('id')
  2337. if not feed_id:
  2338. continue
  2339. feed_title = feed_entry('title')
  2340. title = video_title
  2341. if feed_title:
  2342. title += ' (%s)' % feed_title
  2343. entries.append({
  2344. '_type': 'url_transparent',
  2345. 'ie_key': 'Youtube',
  2346. 'url': smuggle_url(
  2347. base_url + 'watch?v=' + feed_data['id'][0],
  2348. {'force_singlefeed': True}),
  2349. 'title': title,
  2350. })
  2351. feed_ids.append(feed_id)
  2352. self.to_screen(
  2353. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  2354. % (', '.join(feed_ids), video_id))
  2355. return self.playlist_result(
  2356. entries, video_id, video_title, video_description)
  2357. else:
  2358. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2359. if not player_url:
  2360. player_url = self._extract_player_url(webpage)
  2361. formats = []
  2362. itags = collections.defaultdict(set)
  2363. itag_qualities = {}
  2364. q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
  2365. CHUNK_SIZE = 10 << 20
  2366. is_live = video_details.get('isLive')
  2367. streaming_data = player_response.get('streamingData') or {}
  2368. streaming_formats = streaming_data.get('formats') or []
  2369. streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
  2370. def build_fragments(f):
  2371. return LazyList({
  2372. 'url': update_url_query(f['url'], {
  2373. 'range': '{0}-{1}'.format(range_start, min(range_start + CHUNK_SIZE - 1, f['filesize'])),
  2374. }),
  2375. } for range_start in range(0, f['filesize'], CHUNK_SIZE))
  2376. lower = lambda s: s.lower()
  2377. if is_live:
  2378. fetched_timestamp = None
  2379. elif fetched_timestamp is not None:
  2380. # Handle preroll waiting period
  2381. preroll_sleep = self.get_param('youtube_preroll_sleep')
  2382. preroll_sleep = min(6, int_or_none(preroll_sleep, default=preroll_length_ms / 1000))
  2383. fetched_timestamp += preroll_sleep
  2384. for fmt in streaming_formats:
  2385. if fmt.get('targetDurationSec'):
  2386. continue
  2387. itag = str_or_none(fmt.get('itag'))
  2388. audio_track = traverse_obj(fmt, ('audioTrack', T(dict))) or {}
  2389. quality = traverse_obj(fmt, ((
  2390. # The 3gp format (17) in android client has a quality of "small",
  2391. # but is actually worse than other formats
  2392. T(lambda _: 'tiny' if itag == 17 else None),
  2393. ('quality', T(lambda q: q if q and q != 'tiny' else None)),
  2394. ('audioQuality', T(lower)),
  2395. 'quality'), T(txt_or_none)), get_all=False)
  2396. if quality and itag:
  2397. itag_qualities[itag] = quality
  2398. # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
  2399. # (adding `&sq=0` to the URL) and parsing emsg box to determine the
  2400. # number of fragments that would subsequently be requested with (`&sq=N`)
  2401. if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
  2402. continue
  2403. fmt_url = fmt.get('url')
  2404. if not fmt_url:
  2405. sc = compat_parse_qs(fmt.get('signatureCipher'))
  2406. fmt_url = traverse_obj(sc, ('url', -1, T(url_or_none)))
  2407. encrypted_sig = traverse_obj(sc, ('s', -1))
  2408. if not (fmt_url and encrypted_sig):
  2409. continue
  2410. player_url = player_url or self._extract_player_url(webpage)
  2411. if not player_url:
  2412. continue
  2413. try:
  2414. fmt_url = update_url_query(fmt_url, {
  2415. traverse_obj(sc, ('sp', -1)) or 'signature':
  2416. [self._decrypt_signature(encrypted_sig, video_id, player_url)],
  2417. })
  2418. except ExtractorError as e:
  2419. self.report_warning('Signature extraction failed: Some formats may be missing',
  2420. video_id=video_id, only_once=True)
  2421. self.write_debug(error_to_compat_str(e), only_once=True)
  2422. continue
  2423. if parse_qs(fmt_url).get('n'):
  2424. # this and (we assume) all the formats here are n-scrambled
  2425. break
  2426. language_preference = (
  2427. 10 if audio_track.get('audioIsDefault')
  2428. else -10 if 'descriptive' in (traverse_obj(audio_track, ('displayName', T(lower))) or '')
  2429. else -1)
  2430. name = (
  2431. traverse_obj(fmt, ('qualityLabel', T(txt_or_none)))
  2432. or quality.replace('audio_quality_', ''))
  2433. dct = {
  2434. 'format_id': join_nonempty(itag, fmt.get('isDrc') and 'drc'),
  2435. 'url': fmt_url,
  2436. # Format 22 is likely to be damaged: see https://github.com/yt-dlp/yt-dlp/issues/3372
  2437. 'source_preference': ((-5 if itag == '22' else -1)
  2438. + (100 if 'Premium' in name else 0)),
  2439. 'quality': q(quality),
  2440. 'language': join_nonempty(audio_track.get('id', '').split('.')[0],
  2441. 'desc' if language_preference < -1 else '') or None,
  2442. 'language_preference': language_preference,
  2443. # Strictly de-prioritize 3gp formats
  2444. 'preference': -2 if itag == '17' else None,
  2445. }
  2446. if itag:
  2447. itags[itag].add(('https', dct.get('language')))
  2448. self._unthrottle_format_urls(video_id, player_url, dct)
  2449. dct.update(traverse_obj(fmt, {
  2450. 'asr': ('audioSampleRate', T(int_or_none)),
  2451. 'filesize': ('contentLength', T(int_or_none)),
  2452. 'format_note': ('qualityLabel', T(lambda x: x or quality)),
  2453. # for some formats, fps is wrongly returned as 1
  2454. 'fps': ('fps', T(int_or_none), T(lambda f: f if f > 1 else None)),
  2455. 'audio_channels': ('audioChannels', T(int_or_none)),
  2456. 'height': ('height', T(int_or_none)),
  2457. 'has_drm': ('drmFamilies', T(bool)),
  2458. 'tbr': (('averageBitrate', 'bitrate'), T(lambda t: float_or_none(t, 1000))),
  2459. 'width': ('width', T(int_or_none)),
  2460. '_duration_ms': ('approxDurationMs', T(int_or_none)),
  2461. }, get_all=False))
  2462. mime_mobj = re.match(
  2463. r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', fmt.get('mimeType') or '')
  2464. if mime_mobj:
  2465. dct['ext'] = mimetype2ext(mime_mobj.group(1))
  2466. dct.update(parse_codecs(mime_mobj.group(2)))
  2467. single_stream = 'none' in (dct.get(c) for c in ('acodec', 'vcodec'))
  2468. if single_stream and dct.get('ext'):
  2469. dct['container'] = dct['ext'] + '_dash'
  2470. if single_stream or itag == '17':
  2471. # avoid Youtube throttling
  2472. dct.update({
  2473. 'protocol': 'http_dash_segments',
  2474. 'fragments': build_fragments(dct),
  2475. } if dct['filesize'] else {
  2476. 'downloader_options': {'http_chunk_size': CHUNK_SIZE}, # No longer useful?
  2477. })
  2478. if fetched_timestamp:
  2479. dct['available_at'] = fetched_timestamp
  2480. formats.append(dct)
  2481. def process_manifest_format(f, proto, client_name, itag, all_formats=False):
  2482. key = (proto, f.get('language'))
  2483. if not all_formats and key in itags[itag]:
  2484. return False
  2485. itags[itag].add(key)
  2486. if itag:
  2487. f['format_id'] = (
  2488. '{0}-{1}'.format(itag, proto)
  2489. if all_formats or any(p != proto for p, _ in itags[itag])
  2490. else itag)
  2491. if f.get('source_preference') is None:
  2492. f['source_preference'] = -1
  2493. # Deprioritize since its pre-merged m3u8 formats may have lower quality audio streams
  2494. if client_name == 'web_safari' and proto == 'hls' and not is_live:
  2495. f['source_preference'] -= 1
  2496. if itag in ('616', '235'):
  2497. f['format_note'] = join_nonempty(f.get('format_note'), 'Premium', delim=' ')
  2498. f['source_preference'] += 100
  2499. f['quality'] = q(traverse_obj(f, (
  2500. 'format_id', T(lambda s: itag_qualities[s.split('-')[0]])), default=-1))
  2501. if try_call(lambda: f['fps'] <= 1):
  2502. del f['fps']
  2503. if proto == 'hls' and f.get('has_drm'):
  2504. f['has_drm'] = 'maybe'
  2505. f['source_preference'] -= 5
  2506. return True
  2507. hls_manifest_url = streaming_data.get('hlsManifestUrl')
  2508. if hls_manifest_url:
  2509. formats.extend(
  2510. f for f in self._extract_m3u8_formats(
  2511. hls_manifest_url, video_id, 'mp4',
  2512. entry_protocol='m3u8_native', live=is_live, fatal=False)
  2513. if process_manifest_format(
  2514. f, 'hls', None, self._search_regex(
  2515. r'/itag/(\d+)', f['url'], 'itag', default=None)))
  2516. if self.get_param('youtube_include_dash_manifest', True):
  2517. dash_manifest_url = streaming_data.get('dashManifestUrl')
  2518. if dash_manifest_url:
  2519. for f in self._extract_mpd_formats(
  2520. dash_manifest_url, video_id, fatal=False):
  2521. if process_manifest_format(
  2522. f, 'dash', None, f['format_id']):
  2523. f['filesize'] = traverse_obj(f, (
  2524. ('fragment_base_url', 'url'), T(lambda u: self._search_regex(
  2525. r'/clen/(\d+)', u, 'file size', default=None)),
  2526. T(int_or_none)), get_all=False)
  2527. formats.append(f)
  2528. playable_formats = [f for f in formats if not f.get('has_drm')]
  2529. if formats:
  2530. if not playable_formats:
  2531. # If there are no formats that definitely don't have DRM, all have DRM
  2532. self.report_drm(video_id)
  2533. formats[:] = playable_formats
  2534. else:
  2535. if streaming_data.get('licenseInfos'):
  2536. raise ExtractorError(
  2537. 'This video is DRM protected.', expected=True)
  2538. pemr = try_get(
  2539. playability_status,
  2540. lambda x: x['errorScreen']['playerErrorMessageRenderer'],
  2541. dict) or {}
  2542. reason = get_text(pemr.get('reason')) or playability_status.get('reason') or ''
  2543. subreason = pemr.get('subreason')
  2544. if subreason:
  2545. subreason = clean_html(get_text(subreason))
  2546. if subreason == 'The uploader has not made this video available in your country.':
  2547. countries = microformat.get('availableCountries')
  2548. if not countries:
  2549. regions_allowed = search_meta('regionsAllowed')
  2550. countries = regions_allowed.split(',') if regions_allowed else None
  2551. self.raise_geo_restricted(
  2552. subreason, countries)
  2553. reason += '\n' + subreason
  2554. if reason:
  2555. if 'sign in' in reason.lower():
  2556. self.raise_login_required(remove_end(reason, 'This helps protect our community. Learn more'))
  2557. elif traverse_obj(playability_status, ('errorScreen', 'playerCaptchaViewModel', T(dict))):
  2558. reason += '. YouTube is requiring a captcha challenge before playback'
  2559. raise ExtractorError(reason, expected=True)
  2560. self._sort_formats(formats)
  2561. keywords = video_details.get('keywords') or []
  2562. if not keywords and webpage:
  2563. keywords = [
  2564. unescapeHTML(m.group('content'))
  2565. for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
  2566. for keyword in keywords:
  2567. if keyword.startswith('yt:stretch='):
  2568. mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
  2569. if mobj:
  2570. # NB: float is intentional for forcing float division
  2571. w, h = (float(v) for v in mobj.groups())
  2572. if w > 0 and h > 0:
  2573. ratio = w / h
  2574. for f in formats:
  2575. if f.get('vcodec') != 'none':
  2576. f['stretched_ratio'] = ratio
  2577. break
  2578. thumbnails = []
  2579. for container in (video_details, microformat):
  2580. for thumbnail in try_get(
  2581. container,
  2582. lambda x: x['thumbnail']['thumbnails'], list) or []:
  2583. thumbnail_url = url_or_none(thumbnail.get('url'))
  2584. if not thumbnail_url:
  2585. continue
  2586. thumbnails.append({
  2587. 'height': int_or_none(thumbnail.get('height')),
  2588. 'url': update_url(thumbnail_url, query=None, fragment=None),
  2589. 'width': int_or_none(thumbnail.get('width')),
  2590. })
  2591. if thumbnails:
  2592. break
  2593. else:
  2594. thumbnail = search_meta(['og:image', 'twitter:image'])
  2595. if thumbnail:
  2596. thumbnails = [{'url': thumbnail}]
  2597. category = microformat.get('category') or search_meta('genre')
  2598. channel_id = self._extract_channel_id(
  2599. webpage, videodetails=video_details, metadata=microformat)
  2600. duration = int_or_none(
  2601. video_details.get('lengthSeconds')
  2602. or microformat.get('lengthSeconds')) \
  2603. or parse_duration(search_meta('duration'))
  2604. for f in formats:
  2605. # Some formats may have much smaller duration than others (possibly damaged during encoding)
  2606. # but avoid false positives with small duration differences.
  2607. # Ref: https://github.com/yt-dlp/yt-dlp/issues/2823
  2608. if try_call(lambda x: float(x.pop('_duration_ms')) / duration < 500, args=(f,)):
  2609. self.report_warning(
  2610. '{0}: Some possibly damaged formats will be deprioritized'.format(video_id), only_once=True)
  2611. # Strictly de-prioritize damaged formats
  2612. f['preference'] = -10
  2613. owner_profile_url = self._yt_urljoin(self._extract_author_var(
  2614. webpage, 'url', videodetails=video_details, metadata=microformat))
  2615. uploader = self._extract_author_var(
  2616. webpage, 'name', videodetails=video_details, metadata=microformat)
  2617. info = {
  2618. 'id': video_id,
  2619. 'title': self._live_title(video_title) if is_live else video_title,
  2620. 'formats': formats,
  2621. 'thumbnails': thumbnails,
  2622. 'description': video_description,
  2623. 'upload_date': unified_strdate(
  2624. microformat.get('uploadDate')
  2625. or search_meta('uploadDate')),
  2626. 'uploader': uploader,
  2627. 'channel_id': channel_id,
  2628. 'duration': duration,
  2629. 'view_count': int_or_none(
  2630. video_details.get('viewCount')
  2631. or microformat.get('viewCount')
  2632. or search_meta('interactionCount')),
  2633. 'average_rating': float_or_none(video_details.get('averageRating')),
  2634. 'age_limit': 18 if (
  2635. microformat.get('isFamilySafe') is False
  2636. or search_meta('isFamilyFriendly') == 'false'
  2637. or search_meta('og:restrictions:age') == '18+') else 0,
  2638. 'webpage_url': webpage_url,
  2639. 'categories': [category] if category else None,
  2640. 'tags': keywords,
  2641. 'is_live': is_live,
  2642. }
  2643. pctr = traverse_obj(
  2644. (player_response, api_player_response),
  2645. (Ellipsis, 'captions', 'playerCaptionsTracklistRenderer', T(dict)))
  2646. if pctr:
  2647. def process_language(container, base_url, lang_code, query):
  2648. lang_subs = []
  2649. for fmt in self._SUBTITLE_FORMATS:
  2650. query.update({
  2651. 'fmt': fmt,
  2652. # xosf=1 causes undesirable text position data for vtt, json3 & srv* subtitles
  2653. # See: https://github.com/yt-dlp/yt-dlp/issues/13654
  2654. 'xosf': [],
  2655. })
  2656. lang_subs.append({
  2657. 'ext': fmt,
  2658. 'url': update_url_query(base_url, query),
  2659. })
  2660. container[lang_code] = lang_subs
  2661. def process_subtitles():
  2662. subtitles = {}
  2663. for caption_track in traverse_obj(pctr, (
  2664. Ellipsis, 'captionTracks', lambda _, v: (
  2665. v.get('baseUrl') and v.get('languageCode')))):
  2666. base_url = self._yt_urljoin(caption_track['baseUrl'])
  2667. if not base_url:
  2668. continue
  2669. lang_code = caption_track['languageCode']
  2670. if caption_track.get('kind') != 'asr':
  2671. process_language(
  2672. subtitles, base_url, lang_code, {})
  2673. continue
  2674. automatic_captions = {}
  2675. process_language(
  2676. automatic_captions, base_url, lang_code, {})
  2677. for translation_language in traverse_obj(pctr, (
  2678. Ellipsis, 'translationLanguages', lambda _, v: v.get('languageCode'))):
  2679. translation_language_code = translation_language['languageCode']
  2680. process_language(
  2681. automatic_captions, base_url, translation_language_code,
  2682. {'tlang': translation_language_code})
  2683. info['automatic_captions'] = automatic_captions
  2684. info['subtitles'] = subtitles
  2685. process_subtitles()
  2686. parsed_url = compat_urllib_parse_urlparse(url)
  2687. for component in (parsed_url.fragment, parsed_url.query):
  2688. query = compat_parse_qs(component)
  2689. for k, v in query.items():
  2690. for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
  2691. d_k += '_time'
  2692. if d_k not in info and k in s_ks:
  2693. info[d_k] = parse_duration(v[0])
  2694. if video_description:
  2695. # Youtube Music Auto-generated description
  2696. mobj = re.search(r'(?s)(?P<track>[^·\n]+)·(?P<artist>[^\n]+)\n+(?P<album>[^\n]+)(?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?(?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?(.+?\nArtist\s*:\s*(?P<clean_artist>[^\n]+))?.+\nAuto-generated by YouTube\.\s*$', video_description)
  2697. if mobj:
  2698. release_year = mobj.group('release_year')
  2699. release_date = mobj.group('release_date')
  2700. if release_date:
  2701. release_date = release_date.replace('-', '')
  2702. if not release_year:
  2703. release_year = release_date[:4]
  2704. info.update({
  2705. 'album': mobj.group('album'.strip()),
  2706. 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
  2707. 'track': mobj.group('track').strip(),
  2708. 'release_date': release_date,
  2709. 'release_year': int_or_none(release_year),
  2710. })
  2711. initial_data = None
  2712. if webpage:
  2713. initial_data = self._extract_yt_initial_variable(
  2714. webpage, self._YT_INITIAL_DATA_RE, video_id,
  2715. 'yt initial data')
  2716. if not initial_data:
  2717. initial_data = self._call_api(
  2718. 'next', {'videoId': video_id}, video_id, fatal=False)
  2719. initial_sdcr = None
  2720. if initial_data:
  2721. chapters = self._extract_chapters_from_json(
  2722. initial_data, video_id, duration)
  2723. if not chapters:
  2724. for engagment_pannel in (initial_data.get('engagementPanels') or []):
  2725. contents = try_get(
  2726. engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
  2727. list)
  2728. if not contents:
  2729. continue
  2730. def chapter_time(mmlir):
  2731. return parse_duration(
  2732. get_text(mmlir.get('timeDescription')))
  2733. chapters = []
  2734. for next_num, content in enumerate(contents, start=1):
  2735. mmlir = content.get('macroMarkersListItemRenderer') or {}
  2736. start_time = chapter_time(mmlir)
  2737. end_time = (traverse_obj(
  2738. contents, (next_num, 'macroMarkersListItemRenderer', T(chapter_time)))
  2739. if next_num < len(contents) else duration)
  2740. if start_time is None or end_time is None:
  2741. continue
  2742. chapters.append({
  2743. 'start_time': start_time,
  2744. 'end_time': end_time,
  2745. 'title': get_text(mmlir.get('title')),
  2746. })
  2747. if chapters:
  2748. break
  2749. if chapters:
  2750. info['chapters'] = chapters
  2751. contents = try_get(
  2752. initial_data,
  2753. lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
  2754. list) or []
  2755. if not info['channel_id']:
  2756. channel_id = self._extract_channel_id('', renderers=contents)
  2757. if not info['uploader']:
  2758. info['uploader'] = self._extract_author_var('', 'name', renderers=contents)
  2759. if not owner_profile_url:
  2760. owner_profile_url = self._yt_urljoin(self._extract_author_var('', 'url', renderers=contents))
  2761. for content in contents:
  2762. vpir = content.get('videoPrimaryInfoRenderer')
  2763. if vpir:
  2764. stl = vpir.get('superTitleLink')
  2765. if stl:
  2766. stl = get_text(stl)
  2767. if try_get(
  2768. vpir,
  2769. lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
  2770. info['location'] = stl
  2771. else:
  2772. # •? doesn't match, but [•]? does; \xa0 = non-breaking space
  2773. mobj = re.search(r'([^\xa0\s].*?)[\xa0\s]*S(\d+)[\xa0\s]*[•]?[\xa0\s]*E(\d+)', stl)
  2774. if mobj:
  2775. info.update({
  2776. 'series': mobj.group(1),
  2777. 'season_number': int(mobj.group(2)),
  2778. 'episode_number': int(mobj.group(3)),
  2779. })
  2780. for tlb in (try_get(
  2781. vpir,
  2782. lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
  2783. list) or []):
  2784. tbr = traverse_obj(tlb, ('segmentedLikeDislikeButtonRenderer', 'likeButton', 'toggleButtonRenderer'), 'toggleButtonRenderer') or {}
  2785. for getter, regex in [(
  2786. lambda x: x['defaultText']['accessibility']['accessibilityData'],
  2787. r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
  2788. lambda x: x['accessibility'],
  2789. lambda x: x['accessibilityData']['accessibilityData'],
  2790. ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
  2791. label = (try_get(tbr, getter, dict) or {}).get('label')
  2792. if label:
  2793. mobj = re.match(regex, label)
  2794. if mobj:
  2795. info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
  2796. break
  2797. sbr_tooltip = try_get(
  2798. vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
  2799. if sbr_tooltip:
  2800. # however dislike_count was hidden by YT, as if there could ever be dislikable content on YT
  2801. like_count, dislike_count = sbr_tooltip.split(' / ')
  2802. info.update({
  2803. 'like_count': str_to_int(like_count),
  2804. 'dislike_count': str_to_int(dislike_count),
  2805. })
  2806. else:
  2807. info['like_count'] = traverse_obj(vpir, (
  2808. 'videoActions', 'menuRenderer', 'topLevelButtons', Ellipsis,
  2809. 'segmentedLikeDislikeButtonViewModel', 'likeButtonViewModel', 'likeButtonViewModel',
  2810. 'toggleButtonViewModel', 'toggleButtonViewModel', 'defaultButtonViewModel',
  2811. 'buttonViewModel', (('title', ('accessibilityText', T(lambda s: s.split()), Ellipsis))), T(parse_count)),
  2812. get_all=False)
  2813. vsir = content.get('videoSecondaryInfoRenderer')
  2814. if vsir:
  2815. rows = try_get(
  2816. vsir,
  2817. lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
  2818. list) or []
  2819. multiple_songs = False
  2820. for row in rows:
  2821. if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
  2822. multiple_songs = True
  2823. break
  2824. for row in rows:
  2825. mrr = row.get('metadataRowRenderer') or {}
  2826. mrr_title = mrr.get('title')
  2827. if not mrr_title:
  2828. continue
  2829. mrr_title = get_text(mrr['title'])
  2830. mrr_contents_text = get_text(mrr['contents'][0])
  2831. if mrr_title == 'License':
  2832. info['license'] = mrr_contents_text
  2833. elif not multiple_songs:
  2834. if mrr_title == 'Album':
  2835. info['album'] = mrr_contents_text
  2836. elif mrr_title == 'Artist':
  2837. info['artist'] = mrr_contents_text
  2838. elif mrr_title == 'Song':
  2839. info['track'] = mrr_contents_text
  2840. # this is not extraction but spelunking!
  2841. initial_sdcr = traverse_obj(initial_data, (
  2842. 'engagementPanels', Ellipsis, 'engagementPanelSectionListRenderer',
  2843. 'content', 'structuredDescriptionContentRenderer', T(dict)),
  2844. get_all=False)
  2845. carousel_lockups = traverse_obj(initial_sdcr, (
  2846. 'items', Ellipsis, 'videoDescriptionMusicSectionRenderer',
  2847. 'carouselLockups', Ellipsis, T(dict))) or []
  2848. # try to reproduce logic from metadataRowContainerRenderer above (if it still is)
  2849. fields = (('ALBUM', 'album'), ('ARTIST', 'artist'), ('SONG', 'track'), ('LICENSES', 'license'))
  2850. # multiple_songs ?
  2851. if len(carousel_lockups) > 1:
  2852. fields = fields[-1:]
  2853. for info_row in traverse_obj(
  2854. carousel_lockups,
  2855. (0, 'carouselLockupRenderer', 'infoRows', Ellipsis, 'infoRowRenderer'),
  2856. expected_type=dict):
  2857. row_title = traverse_obj(info_row, ('title', 'simpleText'))
  2858. row_text = traverse_obj(info_row, 'defaultMetadata', 'expandedMetadata', expected_type=get_text)
  2859. if not row_text:
  2860. continue
  2861. for name, field in fields:
  2862. if name == row_title and not info.get(field):
  2863. info[field] = row_text
  2864. for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
  2865. v = info.get(s_k)
  2866. if v:
  2867. info[d_k] = v
  2868. self.mark_watched(video_id, player_response)
  2869. # Fallbacks for missing metadata
  2870. if initial_sdcr:
  2871. if info.get('description') is None:
  2872. info['description'] = traverse_obj(initial_sdcr, (
  2873. 'items', Ellipsis, 'expandableVideoDescriptionBodyRenderer',
  2874. 'attributedDescriptionBodyText', 'content', T(compat_str)),
  2875. get_all=False)
  2876. # videoDescriptionHeaderRenderer also has publishDate/channel/handle/ucid, but not needed
  2877. if info.get('title') is None:
  2878. info['title'] = traverse_obj(
  2879. (initial_sdcr, initial_data),
  2880. (0, 'items', Ellipsis, 'videoDescriptionHeaderRenderer', T(dict)),
  2881. (1, 'playerOverlays', 'playerOverlayRenderer', 'videoDetails',
  2882. 'playerOverlayVideoDetailsRenderer', T(dict)),
  2883. expected_type=lambda x: self._get_text(x, 'title'),
  2884. get_all=False)
  2885. return merge_dicts(
  2886. info, {
  2887. 'uploader_id': self._extract_uploader_id(owner_profile_url),
  2888. 'uploader_url': owner_profile_url,
  2889. 'channel_id': channel_id,
  2890. 'channel_url': channel_id and self._yt_urljoin('/channel/' + channel_id),
  2891. 'channel': info['uploader'],
  2892. })
  2893. class YoutubeTabIE(YoutubeBaseInfoExtractor):
  2894. IE_DESC = 'YouTube.com tab'
  2895. _VALID_URL = r'''(?x)
  2896. https?://
  2897. (?:\w+\.)?
  2898. (?:
  2899. youtube(?:kids)?\.com|
  2900. invidio\.us
  2901. )/
  2902. (?:
  2903. (?:channel|c|user|feed|hashtag)/|
  2904. (?:playlist|watch)\?.*?\blist=|
  2905. (?!(?:watch|embed|v|e|results)\b)
  2906. )
  2907. (?P<id>[^/?\#&]+)
  2908. '''
  2909. IE_NAME = 'youtube:tab'
  2910. _TESTS = [{
  2911. # Shorts
  2912. 'url': 'https://www.youtube.com/@SuperCooperShorts/shorts',
  2913. 'playlist_mincount': 5,
  2914. 'info_dict': {
  2915. 'description': 'Short clips from Super Cooper Sundays!',
  2916. 'id': 'UCKMA8kHZ8bPYpnMNaUSxfEQ',
  2917. 'title': 'Super Cooper Shorts - Shorts',
  2918. 'uploader': 'Super Cooper Shorts',
  2919. 'uploader_id': '@SuperCooperShorts',
  2920. },
  2921. }, {
  2922. # Channel that does not have a Shorts tab. Test should just download videos on Home tab instead
  2923. 'url': 'https://www.youtube.com/@emergencyawesome/shorts',
  2924. 'info_dict': {
  2925. 'description': 'md5:592c080c06fef4de3c902c4a8eecd850',
  2926. 'id': 'UCDiFRMQWpcp8_KD4vwIVicw',
  2927. 'title': 'Emergency Awesome - Home',
  2928. },
  2929. 'playlist_mincount': 5,
  2930. 'skip': 'new test page needed to replace `Emergency Awesome - Shorts`',
  2931. }, {
  2932. # playlists, multipage
  2933. 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
  2934. 'playlist_mincount': 94,
  2935. 'info_dict': {
  2936. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  2937. 'title': r're:Igor Kleiner(?: Ph\.D\.)? - Playlists',
  2938. 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
  2939. 'uploader': 'Igor Kleiner',
  2940. 'uploader_id': '@IgorDataScience',
  2941. },
  2942. }, {
  2943. # playlists, multipage, different order
  2944. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2945. 'playlist_mincount': 94,
  2946. 'info_dict': {
  2947. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  2948. 'title': r're:Igor Kleiner(?: Ph\.D\.)? - Playlists',
  2949. 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
  2950. 'uploader': 'Igor Kleiner',
  2951. 'uploader_id': '@IgorDataScience',
  2952. },
  2953. }, {
  2954. # playlists, series
  2955. 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
  2956. 'playlist_mincount': 5,
  2957. 'info_dict': {
  2958. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  2959. 'title': '3Blue1Brown - Playlists',
  2960. 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
  2961. 'uploader': '3Blue1Brown',
  2962. 'uploader_id': '@3blue1brown',
  2963. },
  2964. }, {
  2965. # playlists, singlepage
  2966. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2967. 'playlist_mincount': 4,
  2968. 'info_dict': {
  2969. 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
  2970. 'title': 'ThirstForScience - Playlists',
  2971. 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
  2972. 'uploader': 'ThirstForScience',
  2973. 'uploader_id': '@ThirstForScience',
  2974. },
  2975. }, {
  2976. 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
  2977. 'only_matching': True,
  2978. }, {
  2979. # basic, single video playlist
  2980. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2981. 'info_dict': {
  2982. 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2983. 'title': 'youtube-dl public playlist',
  2984. 'uploader': 'Sergey M.',
  2985. 'uploader_id': '@sergeym.6173',
  2986. 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2987. },
  2988. 'playlist_count': 1,
  2989. }, {
  2990. # empty playlist
  2991. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2992. 'info_dict': {
  2993. 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2994. 'title': 'youtube-dl empty playlist',
  2995. 'uploader': 'Sergey M.',
  2996. 'uploader_id': '@sergeym.6173',
  2997. 'channel_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2998. },
  2999. 'playlist_count': 0,
  3000. }, {
  3001. # Home tab
  3002. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
  3003. 'info_dict': {
  3004. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  3005. 'title': 'lex will - Home',
  3006. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  3007. 'uploader': 'lex will',
  3008. 'uploader_id': '@lexwill718',
  3009. },
  3010. 'playlist_mincount': 2,
  3011. }, {
  3012. # Videos tab
  3013. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
  3014. 'info_dict': {
  3015. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  3016. 'title': 'lex will - Videos',
  3017. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  3018. 'uploader': 'lex will',
  3019. 'uploader_id': '@lexwill718',
  3020. },
  3021. 'playlist_mincount': 975,
  3022. }, {
  3023. # Videos tab, sorted by popular
  3024. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
  3025. 'info_dict': {
  3026. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  3027. 'title': 'lex will - Videos',
  3028. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  3029. 'uploader': 'lex will',
  3030. 'uploader_id': '@lexwill718',
  3031. },
  3032. 'playlist_mincount': 199,
  3033. }, {
  3034. # Playlists tab
  3035. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
  3036. 'info_dict': {
  3037. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  3038. 'title': 'lex will - Playlists',
  3039. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  3040. 'uploader': 'lex will',
  3041. 'uploader_id': '@lexwill718',
  3042. },
  3043. 'playlist_mincount': 17,
  3044. }, {
  3045. # Community tab
  3046. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
  3047. 'info_dict': {
  3048. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  3049. 'title': 'lex will - Community',
  3050. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  3051. 'uploader': 'lex will',
  3052. 'uploader_id': '@lexwill718',
  3053. },
  3054. 'playlist_mincount': 18,
  3055. }, {
  3056. # Channels tab
  3057. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
  3058. 'info_dict': {
  3059. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  3060. 'title': r're:lex will - (?:Home|Channels)',
  3061. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  3062. 'uploader': 'lex will',
  3063. 'uploader_id': '@lexwill718',
  3064. },
  3065. 'playlist_mincount': 75,
  3066. }, {
  3067. # Releases tab
  3068. 'url': 'https://www.youtube.com/@daftpunk/releases',
  3069. 'info_dict': {
  3070. 'id': 'UC_kRDKYrUlrbtrSiyu5Tflg',
  3071. 'title': 'Daft Punk - Releases',
  3072. 'description': 'Daft Punk (1993 - 2021) - Official YouTube Channel',
  3073. 'uploader_id': '@daftpunk',
  3074. 'uploader': 'Daft Punk',
  3075. },
  3076. 'playlist_mincount': 36,
  3077. }, {
  3078. 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  3079. 'only_matching': True,
  3080. }, {
  3081. 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  3082. 'only_matching': True,
  3083. }, {
  3084. 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  3085. 'only_matching': True,
  3086. }, {
  3087. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  3088. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  3089. 'info_dict': {
  3090. 'title': '29C3: Not my department',
  3091. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  3092. 'uploader': 'Christiaan008',
  3093. 'uploader_id': '@ChRiStIaAn008',
  3094. 'channel_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
  3095. },
  3096. 'playlist_count': 96,
  3097. }, {
  3098. 'note': 'Large playlist',
  3099. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  3100. 'info_dict': {
  3101. 'title': 'Uploads from Cauchemar',
  3102. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  3103. 'uploader': 'Cauchemar',
  3104. 'uploader_id': '@Cauchemar89',
  3105. 'channel_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
  3106. },
  3107. 'playlist_mincount': 1123,
  3108. }, {
  3109. # even larger playlist, 8832 videos
  3110. 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
  3111. 'only_matching': True,
  3112. }, {
  3113. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  3114. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  3115. 'info_dict': {
  3116. 'title': 'Uploads from Interstellar Movie',
  3117. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  3118. 'uploader': 'Interstellar Movie',
  3119. 'uploader_id': '@InterstellarMovie',
  3120. 'channel_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
  3121. },
  3122. 'playlist_mincount': 21,
  3123. }, {
  3124. # https://github.com/ytdl-org/youtube-dl/issues/21844
  3125. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  3126. 'info_dict': {
  3127. 'title': 'Data Analysis with Dr Mike Pound',
  3128. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  3129. 'uploader': 'Computerphile',
  3130. 'uploader_id': '@Computerphile',
  3131. 'channel_id': 'UC9-y-6csu5WGm29I7JiwpnA',
  3132. },
  3133. 'playlist_mincount': 11,
  3134. }, {
  3135. 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  3136. 'only_matching': True,
  3137. }, {
  3138. # Playlist URL that does not actually serve a playlist
  3139. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  3140. 'info_dict': {
  3141. 'id': 'FqZTN594JQw',
  3142. 'ext': 'webm',
  3143. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  3144. 'uploader': 'STREEM',
  3145. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  3146. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  3147. 'upload_date': '20150526',
  3148. 'license': 'Standard YouTube License',
  3149. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  3150. 'categories': ['People & Blogs'],
  3151. 'tags': list,
  3152. 'view_count': int,
  3153. 'like_count': int,
  3154. },
  3155. 'params': {
  3156. 'skip_download': True,
  3157. },
  3158. 'skip': 'This video is not available.',
  3159. 'add_ie': [YoutubeIE.ie_key()],
  3160. }, {
  3161. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  3162. 'only_matching': True,
  3163. }, {
  3164. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  3165. 'only_matching': True,
  3166. }, {
  3167. 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
  3168. 'info_dict': {
  3169. 'id': r're:[\da-zA-Z_-]{8,}',
  3170. 'ext': 'mp4',
  3171. 'title': r're:(?s)[A-Z].{20,}',
  3172. 'uploader': 'Sky News',
  3173. 'uploader_id': '@SkyNews',
  3174. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@SkyNews',
  3175. 'upload_date': r're:\d{8}',
  3176. 'description': r're:(?s)(?:.*\n)+SUBSCRIBE to our YouTube channel for more videos: http://www\.youtube\.com/skynews *\n.*',
  3177. 'categories': ['News & Politics'],
  3178. 'tags': list,
  3179. 'like_count': int,
  3180. },
  3181. 'params': {
  3182. 'skip_download': True,
  3183. },
  3184. }, {
  3185. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  3186. 'info_dict': {
  3187. 'id': 'a48o2S1cPoo',
  3188. 'ext': 'mp4',
  3189. 'title': 'The Young Turks - Live Main Show',
  3190. 'uploader': 'The Young Turks',
  3191. 'uploader_id': 'TheYoungTurks',
  3192. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  3193. 'upload_date': '20150715',
  3194. 'license': 'Standard YouTube License',
  3195. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  3196. 'categories': ['News & Politics'],
  3197. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  3198. 'like_count': int,
  3199. },
  3200. 'params': {
  3201. 'skip_download': True,
  3202. },
  3203. 'only_matching': True,
  3204. }, {
  3205. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  3206. 'only_matching': True,
  3207. }, {
  3208. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  3209. 'only_matching': True,
  3210. }, {
  3211. 'url': 'https://www.youtube.com/feed/trending',
  3212. 'only_matching': True,
  3213. }, {
  3214. # needs auth
  3215. 'url': 'https://www.youtube.com/feed/library',
  3216. 'only_matching': True,
  3217. }, {
  3218. # needs auth
  3219. 'url': 'https://www.youtube.com/feed/history',
  3220. 'only_matching': True,
  3221. }, {
  3222. # needs auth
  3223. 'url': 'https://www.youtube.com/feed/subscriptions',
  3224. 'only_matching': True,
  3225. }, {
  3226. # needs auth
  3227. 'url': 'https://www.youtube.com/feed/watch_later',
  3228. 'only_matching': True,
  3229. }, {
  3230. # no longer available?
  3231. 'url': 'https://www.youtube.com/feed/recommended',
  3232. 'only_matching': True,
  3233. }, {
  3234. # inline playlist with not always working continuations
  3235. 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
  3236. 'only_matching': True,
  3237. }, {
  3238. 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
  3239. 'only_matching': True,
  3240. }, {
  3241. 'url': 'https://www.youtube.com/course',
  3242. 'only_matching': True,
  3243. }, {
  3244. 'url': 'https://www.youtube.com/zsecurity',
  3245. 'only_matching': True,
  3246. }, {
  3247. 'url': 'http://www.youtube.com/NASAgovVideo/videos',
  3248. 'only_matching': True,
  3249. }, {
  3250. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  3251. 'only_matching': True,
  3252. }, {
  3253. 'url': 'https://www.youtube.com/hashtag/cctv9',
  3254. 'info_dict': {
  3255. 'id': 'cctv9',
  3256. 'title': '#cctv9',
  3257. },
  3258. 'playlist_mincount': 350,
  3259. }, {
  3260. 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
  3261. 'only_matching': True,
  3262. }, {
  3263. 'note': 'Search tab',
  3264. 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
  3265. 'playlist_mincount': 20,
  3266. 'info_dict': {
  3267. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  3268. 'title': '3Blue1Brown - Search - linear algebra',
  3269. 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
  3270. 'uploader': '3Blue1Brown',
  3271. 'uploader_id': '@3blue1brown',
  3272. 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
  3273. },
  3274. }]
  3275. @classmethod
  3276. def suitable(cls, url):
  3277. return not YoutubeIE.suitable(url) and super(
  3278. YoutubeTabIE, cls).suitable(url)
  3279. @staticmethod
  3280. def _extract_grid_item_renderer(item):
  3281. return traverse_obj(item, (
  3282. T(dict.items), lambda _, k_v: k_v[0].startswith('grid') and k_v[0].endswith('Renderer'),
  3283. 1, T(dict)), get_all=False)
  3284. @staticmethod
  3285. def _get_text(r, k):
  3286. return traverse_obj(
  3287. r, (k, 'runs', 0, 'text'), (k, 'simpleText'),
  3288. expected_type=txt_or_none)
  3289. def _grid_entries(self, grid_renderer):
  3290. for item in traverse_obj(grid_renderer, ('items', Ellipsis, T(dict))):
  3291. lockup_view_model = traverse_obj(item, ('lockupViewModel', T(dict)))
  3292. if lockup_view_model:
  3293. entry = self._extract_lockup_view_model(lockup_view_model)
  3294. if entry:
  3295. yield entry
  3296. continue
  3297. renderer = self._extract_grid_item_renderer(item)
  3298. if not isinstance(renderer, dict):
  3299. continue
  3300. title = self._get_text(renderer, 'title')
  3301. # playlist
  3302. playlist_id = renderer.get('playlistId')
  3303. if playlist_id:
  3304. yield self.url_result(
  3305. 'https://www.youtube.com/playlist?list=%s' % playlist_id,
  3306. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  3307. video_title=title)
  3308. continue
  3309. # video
  3310. video_id = renderer.get('videoId')
  3311. if video_id:
  3312. yield self._extract_video(renderer)
  3313. continue
  3314. # channel
  3315. channel_id = renderer.get('channelId')
  3316. if channel_id:
  3317. title = self._get_text(renderer, 'title')
  3318. yield self.url_result(
  3319. 'https://www.youtube.com/channel/%s' % channel_id,
  3320. ie=YoutubeTabIE.ie_key(), video_title=title)
  3321. continue
  3322. # generic endpoint URL support
  3323. ep_url = urljoin('https://www.youtube.com/', try_get(
  3324. renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
  3325. compat_str))
  3326. if ep_url:
  3327. for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
  3328. if ie.suitable(ep_url):
  3329. yield self.url_result(
  3330. ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
  3331. break
  3332. def _shelf_entries_from_content(self, shelf_renderer):
  3333. content = shelf_renderer.get('content')
  3334. if not isinstance(content, dict):
  3335. return
  3336. renderer = content.get('gridRenderer')
  3337. if renderer:
  3338. # TODO: add support for nested playlists so each shelf is processed
  3339. # as separate playlist
  3340. # TODO: this includes only first N items
  3341. for entry in self._grid_entries(renderer):
  3342. yield entry
  3343. renderer = content.get('horizontalListRenderer')
  3344. if renderer:
  3345. # TODO
  3346. pass
  3347. def _shelf_entries(self, shelf_renderer, skip_channels=False):
  3348. ep = try_get(
  3349. shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  3350. compat_str)
  3351. shelf_url = urljoin('https://www.youtube.com', ep)
  3352. if shelf_url:
  3353. # Skipping links to another channels, note that checking for
  3354. # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
  3355. # will not work
  3356. if skip_channels and '/channels?' in shelf_url:
  3357. return
  3358. title = try_get(
  3359. shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
  3360. yield self.url_result(shelf_url, video_title=title)
  3361. # Shelf may not contain shelf URL, fallback to extraction from content
  3362. for from_ in self._shelf_entries_from_content(shelf_renderer):
  3363. yield from_
  3364. def _playlist_entries(self, video_list_renderer):
  3365. for content in video_list_renderer['contents']:
  3366. if not isinstance(content, dict):
  3367. continue
  3368. renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
  3369. if not isinstance(renderer, dict):
  3370. continue
  3371. video_id = renderer.get('videoId')
  3372. if not video_id:
  3373. continue
  3374. yield self._extract_video(renderer)
  3375. def _extract_lockup_view_model(self, view_model):
  3376. content_id = view_model.get('contentId')
  3377. if not content_id:
  3378. return
  3379. content_type = view_model.get('contentType')
  3380. if content_type == 'LOCKUP_CONTENT_TYPE_VIDEO':
  3381. ie = YoutubeIE
  3382. url = update_url_query(
  3383. 'https://www.youtube.com/watch', {'v': content_id})
  3384. thumb_keys = (None,)
  3385. elif content_type in ('LOCKUP_CONTENT_TYPE_PLAYLIST', 'LOCKUP_CONTENT_TYPE_PODCAST'):
  3386. ie = YoutubeTabIE
  3387. url = update_url_query(
  3388. 'https://www.youtube.com/playlist', {'list': content_id})
  3389. thumb_keys = ('collectionThumbnailViewModel', 'primaryThumbnail')
  3390. else:
  3391. self.report_warning(
  3392. 'Unsupported lockup view model content type "{0}"{1}'.format(content_type, bug_reports_message()),
  3393. only_once=True)
  3394. return
  3395. thumb_keys = ('contentImage',) + thumb_keys + ('thumbnailViewModel', 'image')
  3396. return merge_dicts(self.url_result(
  3397. url, ie=ie.ie_key(), video_id=content_id), {
  3398. 'title': traverse_obj(view_model, (
  3399. 'metadata', 'lockupMetadataViewModel', 'title',
  3400. 'content', T(compat_str))),
  3401. 'thumbnails': self._extract_thumbnails(
  3402. view_model, thumb_keys, final_key='sources'),
  3403. })
  3404. def _extract_shorts_lockup_view_model(self, view_model):
  3405. content_id = traverse_obj(view_model, (
  3406. 'onTap', 'innertubeCommand', 'reelWatchEndpoint', 'videoId',
  3407. T(lambda v: v if YoutubeIE.suitable(v) else None)))
  3408. return merge_dicts(self.url_result(
  3409. content_id, ie=YoutubeIE.ie_key(), video_id=content_id), {
  3410. 'title': traverse_obj(view_model, (
  3411. 'overlayMetadata', 'primaryText', 'content', T(compat_str))),
  3412. 'thumbnails': self._extract_thumbnails(
  3413. view_model, 'thumbnail', final_key='sources'),
  3414. }) if content_id else None
  3415. def _video_entry(self, video_renderer):
  3416. video_id = video_renderer.get('videoId')
  3417. return self._extract_video(video_renderer) if video_id else None
  3418. def _post_thread_entries(self, post_thread_renderer):
  3419. post_renderer = try_get(
  3420. post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
  3421. if not post_renderer:
  3422. return
  3423. # video attachment
  3424. video_renderer = try_get(
  3425. post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
  3426. video_id = None
  3427. if video_renderer:
  3428. entry = self._video_entry(video_renderer)
  3429. if entry:
  3430. yield entry
  3431. # inline video links
  3432. runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
  3433. for run in runs:
  3434. if not isinstance(run, dict):
  3435. continue
  3436. ep_url = try_get(
  3437. run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
  3438. if not ep_url:
  3439. continue
  3440. if not YoutubeIE.suitable(ep_url):
  3441. continue
  3442. ep_video_id = YoutubeIE._match_id(ep_url)
  3443. if video_id == ep_video_id:
  3444. continue
  3445. yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
  3446. def _post_thread_continuation_entries(self, post_thread_continuation):
  3447. for renderer in traverse_obj(post_thread_continuation, (
  3448. 'contents', Ellipsis, 'backstagePostThreadRenderer', T(dict))):
  3449. for from_ in self._post_thread_entries(renderer):
  3450. yield from_
  3451. def _rich_grid_entries(self, contents):
  3452. for content in traverse_obj(
  3453. contents, (Ellipsis, 'richItemRenderer', 'content'),
  3454. expected_type=dict):
  3455. video_renderer = traverse_obj(
  3456. content, 'videoRenderer', 'reelItemRenderer',
  3457. expected_type=dict)
  3458. if video_renderer:
  3459. entry = self._video_entry(video_renderer)
  3460. if entry:
  3461. yield entry
  3462. # shorts item
  3463. shorts_lockup_view_model = content.get('shortsLockupViewModel')
  3464. if shorts_lockup_view_model:
  3465. entry = self._extract_shorts_lockup_view_model(shorts_lockup_view_model)
  3466. if entry:
  3467. yield entry
  3468. # playlist
  3469. renderer = traverse_obj(
  3470. content, 'playlistRenderer', expected_type=dict) or {}
  3471. title = self._get_text(renderer, 'title')
  3472. playlist_id = renderer.get('playlistId')
  3473. if playlist_id:
  3474. yield self.url_result(
  3475. 'https://www.youtube.com/playlist?list=%s' % playlist_id,
  3476. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  3477. video_title=title)
  3478. @staticmethod
  3479. def _build_continuation_query(continuation, ctp=None):
  3480. query = {
  3481. 'ctoken': continuation,
  3482. 'continuation': continuation,
  3483. }
  3484. if ctp:
  3485. query['itct'] = ctp
  3486. return query
  3487. @staticmethod
  3488. def _extract_next_continuation_data(renderer):
  3489. next_continuation = try_get(
  3490. renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
  3491. if not next_continuation:
  3492. return
  3493. continuation = next_continuation.get('continuation')
  3494. if not continuation:
  3495. return
  3496. ctp = next_continuation.get('clickTrackingParams')
  3497. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  3498. @classmethod
  3499. def _extract_continuation(cls, renderer):
  3500. next_continuation = cls._extract_next_continuation_data(renderer)
  3501. if next_continuation:
  3502. return next_continuation
  3503. for command in traverse_obj(renderer, (
  3504. ('contents', 'items', 'rows'), Ellipsis, 'continuationItemRenderer',
  3505. ('continuationEndpoint', ('button', 'buttonRenderer', 'command')),
  3506. (('commandExecutorCommand', 'commands', Ellipsis), None), T(dict))):
  3507. continuation = traverse_obj(command, ('continuationCommand', 'token', T(compat_str)))
  3508. if not continuation:
  3509. continue
  3510. ctp = command.get('clickTrackingParams')
  3511. return cls._build_continuation_query(continuation, ctp)
  3512. def _entries(self, tab, item_id, webpage):
  3513. tab_content = try_get(tab, lambda x: x['content'], dict)
  3514. if not tab_content:
  3515. return
  3516. slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
  3517. if slr_renderer:
  3518. is_channels_tab = tab.get('title') == 'Channels'
  3519. continuation = None
  3520. for is_renderer in traverse_obj(slr_renderer, (
  3521. 'contents', Ellipsis, 'itemSectionRenderer', T(dict))):
  3522. for isr_content in traverse_obj(slr_renderer, (
  3523. 'contents', Ellipsis, T(dict))):
  3524. renderer = isr_content.get('playlistVideoListRenderer')
  3525. if renderer:
  3526. for entry in self._playlist_entries(renderer):
  3527. yield entry
  3528. continuation = self._extract_continuation(renderer)
  3529. continue
  3530. renderer = isr_content.get('gridRenderer')
  3531. if renderer:
  3532. for entry in self._grid_entries(renderer):
  3533. yield entry
  3534. continuation = self._extract_continuation(renderer)
  3535. continue
  3536. renderer = isr_content.get('shelfRenderer')
  3537. if renderer:
  3538. for entry in self._shelf_entries(renderer, not is_channels_tab):
  3539. yield entry
  3540. continue
  3541. renderer = isr_content.get('backstagePostThreadRenderer')
  3542. if renderer:
  3543. for entry in self._post_thread_entries(renderer):
  3544. yield entry
  3545. continuation = self._extract_continuation(renderer)
  3546. continue
  3547. renderer = isr_content.get('videoRenderer')
  3548. if renderer:
  3549. entry = self._video_entry(renderer)
  3550. if entry:
  3551. yield entry
  3552. renderer = isr_content.get('richGridRenderer')
  3553. if renderer:
  3554. for from_ in self._rich_grid_entries(
  3555. traverse_obj(renderer, ('contents', Ellipsis, T(dict)))):
  3556. yield from_
  3557. continuation = self._extract_continuation(renderer)
  3558. continue
  3559. if not continuation:
  3560. continuation = self._extract_continuation(is_renderer)
  3561. if not continuation:
  3562. continuation = self._extract_continuation(slr_renderer)
  3563. else:
  3564. rich_grid_renderer = tab_content.get('richGridRenderer')
  3565. if not rich_grid_renderer:
  3566. return
  3567. for from_ in self._rich_grid_entries(
  3568. traverse_obj(rich_grid_renderer, ('contents', Ellipsis, T(dict)))):
  3569. yield from_
  3570. continuation = self._extract_continuation(rich_grid_renderer)
  3571. ytcfg = self._extract_ytcfg(item_id, webpage)
  3572. client_version = try_get(
  3573. ytcfg, lambda x: x['INNERTUBE_CLIENT_VERSION'], compat_str) or '2.20210407.08.00'
  3574. headers = {
  3575. 'x-youtube-client-name': '1',
  3576. 'x-youtube-client-version': client_version,
  3577. 'content-type': 'application/json',
  3578. }
  3579. context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'], dict) or {
  3580. 'client': {
  3581. 'clientName': 'WEB',
  3582. 'clientVersion': client_version,
  3583. },
  3584. }
  3585. visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
  3586. identity_token = self._extract_identity_token(ytcfg, webpage)
  3587. if identity_token:
  3588. headers['x-youtube-identity-token'] = identity_token
  3589. data = {
  3590. 'context': context,
  3591. }
  3592. for page_num in itertools.count(1):
  3593. if not continuation:
  3594. break
  3595. if visitor_data:
  3596. headers['X-Goog-Visitor-Id'] = visitor_data
  3597. data['continuation'] = continuation['continuation']
  3598. data['clickTracking'] = {
  3599. 'clickTrackingParams': continuation['itct'],
  3600. }
  3601. count = 0
  3602. retries = 3
  3603. while count <= retries:
  3604. try:
  3605. # Downloading page may result in intermittent 5xx HTTP error
  3606. # that is usually worked around with a retry
  3607. response = self._download_json(
  3608. 'https://www.youtube.com/youtubei/v1/browse',
  3609. None, 'Downloading page %d%s' % (page_num, ' (retry #%d)' % count if count else ''),
  3610. query={
  3611. # 'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  3612. 'prettyPrint': 'false',
  3613. },
  3614. headers=headers, data=json.dumps(data).encode('utf8'))
  3615. break
  3616. except ExtractorError as e:
  3617. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  3618. count += 1
  3619. if count <= retries:
  3620. continue
  3621. raise
  3622. if not response:
  3623. break
  3624. visitor_data = try_get(
  3625. response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
  3626. continuation_contents = try_get(
  3627. response, lambda x: x['continuationContents'], dict)
  3628. if continuation_contents:
  3629. continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
  3630. if continuation_renderer:
  3631. for entry in self._playlist_entries(continuation_renderer):
  3632. yield entry
  3633. continuation = self._extract_continuation(continuation_renderer)
  3634. continue
  3635. continuation_renderer = continuation_contents.get('gridContinuation')
  3636. if continuation_renderer:
  3637. for entry in self._grid_entries(continuation_renderer):
  3638. yield entry
  3639. continuation = self._extract_continuation(continuation_renderer)
  3640. continue
  3641. continuation_renderer = continuation_contents.get('itemSectionContinuation')
  3642. if continuation_renderer:
  3643. for entry in self._post_thread_continuation_entries(continuation_renderer):
  3644. yield entry
  3645. continuation = self._extract_continuation(continuation_renderer)
  3646. continue
  3647. on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
  3648. continuation_items = try_get(
  3649. on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
  3650. if continuation_items:
  3651. continuation_item = continuation_items[0]
  3652. if not isinstance(continuation_item, dict):
  3653. continue
  3654. renderer = self._extract_grid_item_renderer(continuation_item)
  3655. if renderer:
  3656. grid_renderer = {'items': continuation_items}
  3657. for entry in self._grid_entries(grid_renderer):
  3658. yield entry
  3659. continuation = self._extract_continuation(grid_renderer)
  3660. continue
  3661. renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
  3662. if renderer:
  3663. video_list_renderer = {'contents': continuation_items}
  3664. for entry in self._playlist_entries(video_list_renderer):
  3665. yield entry
  3666. continuation = self._extract_continuation(video_list_renderer)
  3667. continue
  3668. renderer = continuation_item.get('backstagePostThreadRenderer')
  3669. if renderer:
  3670. continuation_renderer = {'contents': continuation_items}
  3671. for entry in self._post_thread_continuation_entries(continuation_renderer):
  3672. yield entry
  3673. continuation = self._extract_continuation(continuation_renderer)
  3674. continue
  3675. renderer = continuation_item.get('richItemRenderer')
  3676. if renderer:
  3677. for entry in self._rich_grid_entries(continuation_items):
  3678. yield entry
  3679. continuation = self._extract_continuation({'contents': continuation_items})
  3680. continue
  3681. break
  3682. @staticmethod
  3683. def _extract_selected_tab(tabs):
  3684. for tab in tabs:
  3685. renderer = dict_get(tab, ('tabRenderer', 'expandableTabRenderer')) or {}
  3686. if renderer.get('selected') is True:
  3687. return renderer
  3688. else:
  3689. raise ExtractorError('Unable to find selected tab')
  3690. def _extract_uploader(self, metadata, data):
  3691. uploader = {}
  3692. renderers = traverse_obj(data,
  3693. ('sidebar', 'playlistSidebarRenderer', 'items'))
  3694. uploader['channel_id'] = self._extract_channel_id('', metadata=metadata, renderers=renderers)
  3695. uploader['uploader'] = (
  3696. self._extract_author_var('', 'name', renderers=renderers)
  3697. or self._extract_author_var('', 'name', metadata=metadata))
  3698. uploader['uploader_url'] = self._yt_urljoin(
  3699. self._extract_author_var('', 'url', metadata=metadata, renderers=renderers))
  3700. uploader['uploader_id'] = self._extract_uploader_id(uploader['uploader_url'])
  3701. uploader['channel'] = uploader['uploader']
  3702. return uploader
  3703. def _extract_and_report_alerts(self, data, expected=True, fatal=True, only_once=False):
  3704. def alerts():
  3705. for alert in traverse_obj(data, ('alerts', Ellipsis), expected_type=dict):
  3706. alert_dict = traverse_obj(
  3707. alert, 'alertRenderer', None, expected_type=dict, get_all=False)
  3708. alert_type = traverse_obj(alert_dict, 'type')
  3709. if not alert_type:
  3710. continue
  3711. message = self._get_text(alert_dict, 'text')
  3712. if message:
  3713. yield alert_type, message
  3714. errors, warnings = [], []
  3715. _IGNORED_WARNINGS = T('Unavailable videos will be hidden during playback')
  3716. for alert_type, alert_message in alerts():
  3717. if alert_type.lower() == 'error' and fatal:
  3718. errors.append([alert_type, alert_message])
  3719. elif alert_message not in _IGNORED_WARNINGS:
  3720. warnings.append([alert_type, alert_message])
  3721. for alert_type, alert_message in itertools.chain(warnings, errors[:-1]):
  3722. self.report_warning(
  3723. 'YouTube said: %s - %s' % (alert_type, alert_message),
  3724. only_once=only_once)
  3725. if errors:
  3726. raise ExtractorError(
  3727. 'YouTube said: %s' % (errors[-1][1],), expected=expected)
  3728. def _extract_from_tabs(self, item_id, webpage, data, tabs):
  3729. selected_tab = self._extract_selected_tab(tabs)
  3730. renderer = traverse_obj(data, ('metadata', 'channelMetadataRenderer'),
  3731. expected_type=dict) or {}
  3732. playlist_id = item_id
  3733. title = description = None
  3734. if renderer:
  3735. channel_title = txt_or_none(renderer.get('title')) or item_id
  3736. tab_title = txt_or_none(selected_tab.get('title'))
  3737. title = join_nonempty(
  3738. channel_title or item_id, tab_title,
  3739. txt_or_none(selected_tab.get('expandedText')),
  3740. delim=' - ')
  3741. description = txt_or_none(renderer.get('description'))
  3742. playlist_id = txt_or_none(renderer.get('externalId')) or playlist_id
  3743. else:
  3744. renderer = traverse_obj(data,
  3745. ('metadata', 'playlistMetadataRenderer'),
  3746. ('header', 'hashtagHeaderRenderer'),
  3747. expected_type=dict) or {}
  3748. title = traverse_obj(renderer, 'title', ('hashtag', 'simpleText'),
  3749. expected_type=txt_or_none)
  3750. playlist = self.playlist_result(
  3751. self._entries(selected_tab, item_id, webpage),
  3752. playlist_id=playlist_id, playlist_title=title,
  3753. playlist_description=description)
  3754. return merge_dicts(playlist, self._extract_uploader(renderer, data))
  3755. def _extract_from_playlist(self, item_id, url, data, playlist):
  3756. title = traverse_obj((playlist, data),
  3757. (0, 'title'), (1, 'titleText', 'simpleText'),
  3758. expected_type=txt_or_none)
  3759. playlist_id = txt_or_none(playlist.get('playlistId')) or item_id
  3760. # Inline playlist rendition continuation does not always work
  3761. # at Youtube side, so delegating regular tab-based playlist URL
  3762. # processing whenever possible.
  3763. playlist_url = urljoin(url, traverse_obj(
  3764. playlist, ('endpoint', 'commandMetadata', 'webCommandMetadata', 'url'),
  3765. expected_type=url_or_none))
  3766. if playlist_url and playlist_url != url:
  3767. return self.url_result(
  3768. playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  3769. video_title=title)
  3770. return self.playlist_result(
  3771. self._playlist_entries(playlist), playlist_id=playlist_id,
  3772. playlist_title=title)
  3773. def _extract_identity_token(self, ytcfg, webpage):
  3774. if ytcfg:
  3775. token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
  3776. if token:
  3777. return token
  3778. return self._search_regex(
  3779. r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
  3780. 'identity token', default=None)
  3781. def _real_extract(self, url):
  3782. item_id = self._match_id(url)
  3783. url = update_url(url, netloc='www.youtube.com')
  3784. qs = parse_qs(url)
  3785. def qs_get(key, default=None):
  3786. return qs.get(key, [default])[-1]
  3787. # Go around for /feeds/videos.xml?playlist_id={pl_id}
  3788. if item_id == 'feeds' and '/feeds/videos.xml?' in url:
  3789. playlist_id = qs_get('playlist_id')
  3790. if playlist_id:
  3791. return self.url_result(
  3792. update_url_query('https://www.youtube.com/playlist', {
  3793. 'list': playlist_id,
  3794. }), ie=self.ie_key(), video_id=playlist_id)
  3795. # Handle both video/playlist URLs
  3796. video_id = qs_get('v')
  3797. playlist_id = qs_get('list')
  3798. if video_id and playlist_id:
  3799. if self._downloader.params.get('noplaylist'):
  3800. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  3801. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  3802. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  3803. webpage = self._download_webpage(url, item_id)
  3804. data = self._extract_yt_initial_data(item_id, webpage)
  3805. tabs = try_get(
  3806. data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
  3807. if tabs:
  3808. return self._extract_from_tabs(item_id, webpage, data, tabs)
  3809. playlist = try_get(
  3810. data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
  3811. if playlist:
  3812. return self._extract_from_playlist(item_id, url, data, playlist)
  3813. # Fallback to video extraction if no playlist alike page is recognized.
  3814. # First check for the current video then try the v attribute of URL query.
  3815. video_id = try_get(
  3816. data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
  3817. compat_str) or video_id
  3818. if video_id:
  3819. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  3820. # Capture and output alerts
  3821. self._extract_and_report_alerts(data)
  3822. # Failed to recognize
  3823. raise ExtractorError('Unable to recognize tab page')
  3824. class YoutubePlaylistIE(InfoExtractor):
  3825. IE_DESC = 'YouTube.com playlists'
  3826. _VALID_URL = r'''(?x)(?:
  3827. (?:https?://)?
  3828. (?:\w+\.)?
  3829. (?:
  3830. (?:
  3831. youtube(?:kids)?\.com|
  3832. invidio\.us
  3833. )
  3834. /.*?\?.*?\blist=
  3835. )?
  3836. (?P<id>%(playlist_id)s)
  3837. )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  3838. IE_NAME = 'youtube:playlist'
  3839. _TESTS = [{
  3840. 'note': 'issue #673',
  3841. 'url': 'PLBB231211A4F62143',
  3842. 'info_dict': {
  3843. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  3844. 'id': 'PLBB231211A4F62143',
  3845. 'uploader': 'Wickman',
  3846. 'uploader_id': '@WickmanVT',
  3847. 'channel_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
  3848. },
  3849. 'playlist_mincount': 29,
  3850. }, {
  3851. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  3852. 'info_dict': {
  3853. 'title': 'YDL_safe_search',
  3854. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  3855. },
  3856. 'playlist_count': 2,
  3857. 'skip': 'This playlist is private',
  3858. }, {
  3859. 'note': 'embedded',
  3860. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  3861. # TODO: full playlist requires _reload_with_unavailable_videos()
  3862. # 'playlist_count': 4,
  3863. 'playlist_mincount': 1,
  3864. 'info_dict': {
  3865. 'title': 'JODA15',
  3866. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  3867. 'uploader': 'milan',
  3868. 'uploader_id': '@milan5503',
  3869. 'channel_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  3870. },
  3871. }, {
  3872. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  3873. 'playlist_mincount': 455,
  3874. 'info_dict': {
  3875. 'title': '2018 Chinese New Singles (11/6 updated)',
  3876. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  3877. 'uploader': 'LBK',
  3878. 'uploader_id': '@music_king',
  3879. 'channel_id': 'UC21nz3_MesPLqtDqwdvnoxA',
  3880. },
  3881. }, {
  3882. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  3883. 'only_matching': True,
  3884. }, {
  3885. # music album playlist
  3886. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  3887. 'only_matching': True,
  3888. }]
  3889. @classmethod
  3890. def suitable(cls, url):
  3891. if YoutubeTabIE.suitable(url):
  3892. return False
  3893. if parse_qs(url).get('v', [None])[0]:
  3894. return False
  3895. return super(YoutubePlaylistIE, cls).suitable(url)
  3896. def _real_extract(self, url):
  3897. playlist_id = self._match_id(url)
  3898. qs = parse_qs(url)
  3899. if not qs:
  3900. qs = {'list': playlist_id}
  3901. return self.url_result(
  3902. update_url_query('https://www.youtube.com/playlist', qs),
  3903. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  3904. class YoutubeYtBeIE(InfoExtractor):
  3905. _VALID_URL = r'https?://youtu\.be/(?P<id>[0-9A-Za-z_-]{11})/*?.*?\blist=(?P<playlist_id>%(playlist_id)s)' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  3906. _TESTS = [{
  3907. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  3908. 'info_dict': {
  3909. 'id': 'yeWKywCrFtk',
  3910. 'ext': 'mp4',
  3911. 'title': 'Small Scale Baler and Braiding Rugs',
  3912. 'uploader': 'Backus-Page House Museum',
  3913. 'uploader_id': '@backuspagemuseum',
  3914. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@backuspagemuseum',
  3915. 'upload_date': '20161008',
  3916. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  3917. 'categories': ['Nonprofits & Activism'],
  3918. 'tags': list,
  3919. 'like_count': int,
  3920. },
  3921. 'params': {
  3922. 'noplaylist': True,
  3923. 'skip_download': True,
  3924. },
  3925. }, {
  3926. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  3927. 'only_matching': True,
  3928. }]
  3929. def _real_extract(self, url):
  3930. mobj = re.match(self._VALID_URL, url)
  3931. video_id = mobj.group('id')
  3932. playlist_id = mobj.group('playlist_id')
  3933. return self.url_result(
  3934. update_url_query('https://www.youtube.com/watch', {
  3935. 'v': video_id,
  3936. 'list': playlist_id,
  3937. 'feature': 'youtu.be',
  3938. }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  3939. class YoutubeYtUserIE(InfoExtractor):
  3940. _VALID_URL = r'ytuser:(?P<id>.+)'
  3941. _TESTS = [{
  3942. 'url': 'ytuser:phihag',
  3943. 'only_matching': True,
  3944. }]
  3945. def _real_extract(self, url):
  3946. user_id = self._match_id(url)
  3947. return self.url_result(
  3948. 'https://www.youtube.com/user/%s' % user_id,
  3949. ie=YoutubeTabIE.ie_key(), video_id=user_id)
  3950. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  3951. IE_NAME = 'youtube:favorites'
  3952. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  3953. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  3954. _LOGIN_REQUIRED = True
  3955. _TESTS = [{
  3956. 'url': ':ytfav',
  3957. 'only_matching': True,
  3958. }, {
  3959. 'url': ':ytfavorites',
  3960. 'only_matching': True,
  3961. }]
  3962. def _real_extract(self, _):
  3963. return self.url_result(
  3964. 'https://www.youtube.com/playlist?list=LL',
  3965. ie=YoutubeTabIE.ie_key())
  3966. class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
  3967. IE_DESC = 'YouTube.com searches'
  3968. IE_NAME = 'youtube:search'
  3969. _SEARCH_KEY = 'ytsearch'
  3970. _SEARCH_PARAMS = 'EgIQAQ%3D%3D' # Videos only
  3971. _MAX_RESULTS = float('inf')
  3972. _TESTS = [{
  3973. 'url': 'ytsearch10:youtube-dl test video',
  3974. 'playlist_count': 10,
  3975. 'info_dict': {
  3976. 'id': 'youtube-dl test video',
  3977. 'title': 'youtube-dl test video',
  3978. },
  3979. }]
  3980. def _get_n_results(self, query, n):
  3981. """Get a specified number of results for a query"""
  3982. entries = itertools.islice(self._search_results(query, self._SEARCH_PARAMS), 0, None if n == float('inf') else n)
  3983. return self.playlist_result(entries, query, query)
  3984. class YoutubeSearchDateIE(YoutubeSearchIE):
  3985. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  3986. _SEARCH_KEY = 'ytsearchdate'
  3987. IE_DESC = 'YouTube.com searches, newest videos first'
  3988. _SEARCH_PARAMS = 'CAISAhAB' # Videos only, sorted by date
  3989. _TESTS = [{
  3990. 'url': 'ytsearchdate10:youtube-dl test video',
  3991. 'playlist_count': 10,
  3992. 'info_dict': {
  3993. 'id': 'youtube-dl test video',
  3994. 'title': 'youtube-dl test video',
  3995. },
  3996. }]
  3997. class YoutubeSearchURLIE(YoutubeBaseInfoExtractor):
  3998. IE_DESC = 'YouTube search URLs with sorting and filter support'
  3999. IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
  4000. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
  4001. _TESTS = [{
  4002. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  4003. 'playlist_mincount': 5,
  4004. 'info_dict': {
  4005. 'id': 'youtube-dl test video',
  4006. 'title': 'youtube-dl test video',
  4007. },
  4008. 'params': {'playlistend': 5},
  4009. }, {
  4010. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  4011. 'only_matching': True,
  4012. }]
  4013. def _real_extract(self, url):
  4014. qs = parse_qs(url)
  4015. query = (qs.get('search_query') or qs.get('q'))[-1]
  4016. params = qs.get('sp', ('',))[-1]
  4017. return self.playlist_result(self._search_results(query, params), query, query)
  4018. class YoutubeFeedsInfoExtractor(YoutubeTabIE):
  4019. """
  4020. Base class for feed extractors
  4021. Subclasses must define the _FEED_NAME property.
  4022. """
  4023. _LOGIN_REQUIRED = True
  4024. @property
  4025. def IE_NAME(self):
  4026. return 'youtube:%s' % self._FEED_NAME
  4027. def _real_initialize(self):
  4028. self._login()
  4029. def _real_extract(self, _):
  4030. return self.url_result(
  4031. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  4032. ie=YoutubeTabIE.ie_key())
  4033. class YoutubeWatchLaterIE(InfoExtractor):
  4034. IE_NAME = 'youtube:watchlater'
  4035. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  4036. _VALID_URL = r':ytwatchlater'
  4037. _TESTS = [{
  4038. 'url': ':ytwatchlater',
  4039. 'only_matching': True,
  4040. }]
  4041. def _real_extract(self, _):
  4042. return self.url_result(
  4043. 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
  4044. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  4045. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  4046. _VALID_URL = r':ytrec(?:ommended)?'
  4047. _FEED_NAME = 'recommended'
  4048. _TESTS = [{
  4049. 'url': ':ytrec',
  4050. 'only_matching': True,
  4051. }, {
  4052. 'url': ':ytrecommended',
  4053. 'only_matching': True,
  4054. }]
  4055. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  4056. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  4057. _VALID_URL = r':ytsubs(?:criptions)?'
  4058. _FEED_NAME = 'subscriptions'
  4059. _TESTS = [{
  4060. 'url': ':ytsubs',
  4061. 'only_matching': True,
  4062. }, {
  4063. 'url': ':ytsubscriptions',
  4064. 'only_matching': True,
  4065. }]
  4066. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  4067. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  4068. _VALID_URL = r':ythistory'
  4069. _FEED_NAME = 'history'
  4070. _TESTS = [{
  4071. 'url': ':ythistory',
  4072. 'only_matching': True,
  4073. }]
  4074. class YoutubeTruncatedURLIE(InfoExtractor):
  4075. IE_NAME = 'youtube:truncated_url'
  4076. IE_DESC = False # Do not list
  4077. _VALID_URL = r'''(?x)
  4078. (?:https?://)?
  4079. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  4080. (?:watch\?(?:
  4081. feature=[a-z_]+|
  4082. annotation_id=annotation_[^&]+|
  4083. x-yt-cl=[0-9]+|
  4084. hl=[^&]*|
  4085. t=[0-9]+
  4086. )?
  4087. |
  4088. attribution_link\?a=[^&]+
  4089. )
  4090. $
  4091. '''
  4092. _TESTS = [{
  4093. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  4094. 'only_matching': True,
  4095. }, {
  4096. 'url': 'https://www.youtube.com/watch?',
  4097. 'only_matching': True,
  4098. }, {
  4099. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  4100. 'only_matching': True,
  4101. }, {
  4102. 'url': 'https://www.youtube.com/watch?feature=foo',
  4103. 'only_matching': True,
  4104. }, {
  4105. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  4106. 'only_matching': True,
  4107. }, {
  4108. 'url': 'https://www.youtube.com/watch?t=2372',
  4109. 'only_matching': True,
  4110. }]
  4111. def _real_extract(self, _):
  4112. raise ExtractorError(
  4113. 'Did you forget to quote the URL? Remember that & is a meta '
  4114. 'character in most shells, so you want to put the URL in quotes, '
  4115. 'like youtube-dl '
  4116. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  4117. ' or simply youtube-dl BaW_jenozKc .',
  4118. expected=True)
  4119. class YoutubeTruncatedIDIE(InfoExtractor):
  4120. IE_NAME = 'youtube:truncated_id'
  4121. IE_DESC = False # Do not list
  4122. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  4123. _TESTS = [{
  4124. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  4125. 'only_matching': True,
  4126. }]
  4127. def _real_extract(self, url):
  4128. video_id = self._match_id(url)
  4129. raise ExtractorError(
  4130. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  4131. expected=True)