youtube.py 159 KB

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