youtube.py 192 KB

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