youtube.py 170 KB

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