youtube.py 186 KB

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