youtube.py 179 KB

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