youtube.py 176 KB

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