youtube.py 185 KB

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