youtube.py 159 KB

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