youtube.py 179 KB

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