youtube.py 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680
  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. )
  20. from ..jsinterp import JSInterpreter
  21. from ..utils import (
  22. ExtractorError,
  23. clean_html,
  24. dict_get,
  25. error_to_compat_str,
  26. float_or_none,
  27. extract_attributes,
  28. get_element_by_attribute,
  29. int_or_none,
  30. js_to_json,
  31. LazyList,
  32. merge_dicts,
  33. mimetype2ext,
  34. parse_codecs,
  35. parse_duration,
  36. parse_qs,
  37. qualities,
  38. remove_start,
  39. smuggle_url,
  40. str_or_none,
  41. str_to_int,
  42. traverse_obj,
  43. try_get,
  44. unescapeHTML,
  45. unified_strdate,
  46. unsmuggle_url,
  47. update_url,
  48. update_url_query,
  49. url_or_none,
  50. urlencode_postdata,
  51. urljoin,
  52. )
  53. class YoutubeBaseInfoExtractor(InfoExtractor):
  54. """Provide base functions for Youtube extractors"""
  55. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  56. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  57. _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
  58. _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
  59. _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
  60. _NETRC_MACHINE = 'youtube'
  61. # If True it will raise an error if no login info is provided
  62. _LOGIN_REQUIRED = False
  63. _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM)'
  64. def _login(self):
  65. """
  66. Attempt to log in to YouTube.
  67. True is returned if successful or skipped.
  68. False is returned if login failed.
  69. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  70. """
  71. username, password = self._get_login_info()
  72. # No authentication to be performed
  73. if username is None:
  74. if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
  75. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  76. return True
  77. login_page = self._download_webpage(
  78. self._LOGIN_URL, None,
  79. note='Downloading login page',
  80. errnote='unable to fetch login page', fatal=False)
  81. if login_page is False:
  82. return
  83. login_form = self._hidden_inputs(login_page)
  84. def req(url, f_req, note, errnote):
  85. data = login_form.copy()
  86. data.update({
  87. 'pstMsg': 1,
  88. 'checkConnection': 'youtube',
  89. 'checkedDomains': 'youtube',
  90. 'hl': 'en',
  91. 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
  92. 'f.req': json.dumps(f_req),
  93. 'flowName': 'GlifWebSignIn',
  94. 'flowEntry': 'ServiceLogin',
  95. # TODO: reverse actual botguard identifier generation algo
  96. 'bgRequest': '["identifier",""]',
  97. })
  98. return self._download_json(
  99. url, None, note=note, errnote=errnote,
  100. transform_source=lambda s: re.sub(r'^[^[]*', '', s),
  101. fatal=False,
  102. data=urlencode_postdata(data), headers={
  103. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  104. 'Google-Accounts-XSRF': 1,
  105. })
  106. def warn(message):
  107. self._downloader.report_warning(message)
  108. lookup_req = [
  109. username,
  110. None, [], None, 'US', None, None, 2, False, True,
  111. [
  112. None, None,
  113. [2, 1, None, 1,
  114. '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',
  115. None, [], 4],
  116. 1, [None, None, []], None, None, None, True
  117. ],
  118. username,
  119. ]
  120. lookup_results = req(
  121. self._LOOKUP_URL, lookup_req,
  122. 'Looking up account info', 'Unable to look up account info')
  123. if lookup_results is False:
  124. return False
  125. user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
  126. if not user_hash:
  127. warn('Unable to extract user hash')
  128. return False
  129. challenge_req = [
  130. user_hash,
  131. None, 1, None, [1, None, None, None, [password, None, True]],
  132. [
  133. 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],
  134. 1, [None, None, []], None, None, None, True
  135. ]]
  136. challenge_results = req(
  137. self._CHALLENGE_URL, challenge_req,
  138. 'Logging in', 'Unable to log in')
  139. if challenge_results is False:
  140. return
  141. login_res = try_get(challenge_results, lambda x: x[0][5], list)
  142. if login_res:
  143. login_msg = try_get(login_res, lambda x: x[5], compat_str)
  144. warn(
  145. 'Unable to login: %s' % 'Invalid password'
  146. if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
  147. return False
  148. res = try_get(challenge_results, lambda x: x[0][-1], list)
  149. if not res:
  150. warn('Unable to extract result entry')
  151. return False
  152. login_challenge = try_get(res, lambda x: x[0][0], list)
  153. if login_challenge:
  154. challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
  155. if challenge_str == 'TWO_STEP_VERIFICATION':
  156. # SEND_SUCCESS - TFA code has been successfully sent to phone
  157. # QUOTA_EXCEEDED - reached the limit of TFA codes
  158. status = try_get(login_challenge, lambda x: x[5], compat_str)
  159. if status == 'QUOTA_EXCEEDED':
  160. warn('Exceeded the limit of TFA codes, try later')
  161. return False
  162. tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
  163. if not tl:
  164. warn('Unable to extract TL')
  165. return False
  166. tfa_code = self._get_tfa_info('2-step verification code')
  167. if not tfa_code:
  168. warn(
  169. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  170. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  171. return False
  172. tfa_code = remove_start(tfa_code, 'G-')
  173. tfa_req = [
  174. user_hash, None, 2, None,
  175. [
  176. 9, None, None, None, None, None, None, None,
  177. [None, tfa_code, True, 2]
  178. ]]
  179. tfa_results = req(
  180. self._TFA_URL.format(tl), tfa_req,
  181. 'Submitting TFA code', 'Unable to submit TFA code')
  182. if tfa_results is False:
  183. return False
  184. tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
  185. if tfa_res:
  186. tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
  187. warn(
  188. 'Unable to finish TFA: %s' % 'Invalid TFA code'
  189. if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
  190. return False
  191. check_cookie_url = try_get(
  192. tfa_results, lambda x: x[0][-1][2], compat_str)
  193. else:
  194. CHALLENGES = {
  195. 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
  196. 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
  197. 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
  198. }
  199. challenge = CHALLENGES.get(
  200. challenge_str,
  201. '%s returned error %s.' % (self.IE_NAME, challenge_str))
  202. warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
  203. return False
  204. else:
  205. check_cookie_url = try_get(res, lambda x: x[2], compat_str)
  206. if not check_cookie_url:
  207. warn('Unable to extract CheckCookie URL')
  208. return False
  209. check_cookie_results = self._download_webpage(
  210. check_cookie_url, None, 'Checking cookie', fatal=False)
  211. if check_cookie_results is False:
  212. return False
  213. if 'https://myaccount.google.com/' not in check_cookie_results:
  214. warn('Unable to log in')
  215. return False
  216. return True
  217. def _initialize_consent(self):
  218. cookies = self._get_cookies('https://www.youtube.com/')
  219. if cookies.get('__Secure-3PSID'):
  220. return
  221. consent_id = None
  222. consent = cookies.get('CONSENT')
  223. if consent:
  224. if 'YES' in consent.value:
  225. return
  226. consent_id = self._search_regex(
  227. r'PENDING\+(\d+)', consent.value, 'consent', default=None)
  228. if not consent_id:
  229. consent_id = random.randint(100, 999)
  230. self._set_cookie('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id)
  231. def _real_initialize(self):
  232. self._initialize_consent()
  233. if self._downloader is None:
  234. return
  235. if not self._login():
  236. return
  237. _DEFAULT_API_DATA = {
  238. 'context': {
  239. 'client': {
  240. 'clientName': 'WEB',
  241. 'clientVersion': '2.20201021.03.00',
  242. }
  243. },
  244. }
  245. _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
  246. _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
  247. _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
  248. def _call_api(self, ep, query, video_id, fatal=True, headers=None):
  249. data = self._DEFAULT_API_DATA.copy()
  250. data.update(query)
  251. real_headers = {'content-type': 'application/json'}
  252. if headers:
  253. real_headers.update(headers)
  254. return self._download_json(
  255. 'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
  256. note='Downloading API JSON', errnote='Unable to download API page',
  257. data=json.dumps(data).encode('utf8'), fatal=fatal,
  258. headers=real_headers,
  259. query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
  260. def _extract_yt_initial_data(self, video_id, webpage):
  261. return self._parse_json(
  262. self._search_regex(
  263. (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
  264. self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
  265. video_id)
  266. def _extract_ytcfg(self, video_id, webpage):
  267. return self._parse_json(
  268. self._search_regex(
  269. r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
  270. default='{}'), video_id, fatal=False) or {}
  271. def _extract_video(self, renderer):
  272. video_id = renderer['videoId']
  273. title = try_get(
  274. renderer,
  275. (lambda x: x['title']['runs'][0]['text'],
  276. lambda x: x['title']['simpleText'],
  277. lambda x: x['headline']['simpleText']), compat_str)
  278. description = try_get(
  279. renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
  280. compat_str)
  281. duration = parse_duration(try_get(
  282. renderer, lambda x: x['lengthText']['simpleText'], compat_str))
  283. view_count_text = try_get(
  284. renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
  285. view_count = str_to_int(self._search_regex(
  286. r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
  287. 'view count', default=None))
  288. uploader = try_get(
  289. renderer,
  290. (lambda x: x['ownerText']['runs'][0]['text'],
  291. lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
  292. return {
  293. '_type': 'url',
  294. 'ie_key': YoutubeIE.ie_key(),
  295. 'id': video_id,
  296. 'url': video_id,
  297. 'title': title,
  298. 'description': description,
  299. 'duration': duration,
  300. 'view_count': view_count,
  301. 'uploader': uploader,
  302. }
  303. def _search_results(self, query, params):
  304. data = {
  305. 'context': {
  306. 'client': {
  307. 'clientName': 'WEB',
  308. 'clientVersion': '2.20201021.03.00',
  309. }
  310. },
  311. 'query': query,
  312. }
  313. if params:
  314. data['params'] = params
  315. for page_num in itertools.count(1):
  316. search = self._download_json(
  317. 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  318. video_id='query "%s"' % query,
  319. note='Downloading page %s' % page_num,
  320. errnote='Unable to download API page', fatal=False,
  321. data=json.dumps(data).encode('utf8'),
  322. headers={'content-type': 'application/json'})
  323. if not search:
  324. break
  325. slr_contents = try_get(
  326. search,
  327. (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
  328. lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
  329. list)
  330. if not slr_contents:
  331. break
  332. for slr_content in slr_contents:
  333. isr_contents = try_get(
  334. slr_content,
  335. lambda x: x['itemSectionRenderer']['contents'],
  336. list)
  337. if not isr_contents:
  338. continue
  339. for content in isr_contents:
  340. if not isinstance(content, dict):
  341. continue
  342. video = content.get('videoRenderer')
  343. if not isinstance(video, dict):
  344. continue
  345. video_id = video.get('videoId')
  346. if not video_id:
  347. continue
  348. yield self._extract_video(video)
  349. token = try_get(
  350. slr_contents,
  351. lambda x: x[-1]['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
  352. compat_str)
  353. if not token:
  354. break
  355. data['continuation'] = token
  356. @staticmethod
  357. def _owner_endpoints_path():
  358. return [
  359. Ellipsis,
  360. lambda k, _: k.endswith('SecondaryInfoRenderer'),
  361. ('owner', 'videoOwner'), 'videoOwnerRenderer', 'title',
  362. 'runs', Ellipsis]
  363. def _extract_channel_id(self, webpage, videodetails={}, metadata={}, renderers=[]):
  364. channel_id = None
  365. if any((videodetails, metadata, renderers)):
  366. channel_id = (
  367. traverse_obj(videodetails, 'channelId')
  368. or traverse_obj(metadata, 'externalChannelId', 'externalId')
  369. or traverse_obj(renderers,
  370. self._owner_endpoints_path() + [
  371. 'navigationEndpoint', 'browseEndpoint', 'browseId'],
  372. get_all=False)
  373. )
  374. return channel_id or self._html_search_meta(
  375. 'channelId', webpage, 'channel id', default=None)
  376. def _extract_author_var(self, webpage, var_name,
  377. videodetails={}, metadata={}, renderers=[]):
  378. result = None
  379. paths = {
  380. # (HTML, videodetails, metadata, renderers)
  381. 'name': ('content', 'author', (('ownerChannelName', None), 'title'), ['text']),
  382. 'url': ('href', 'ownerProfileUrl', 'vanityChannelUrl',
  383. ['navigationEndpoint', 'browseEndpoint', 'canonicalBaseUrl'])
  384. }
  385. if any((videodetails, metadata, renderers)):
  386. result = (
  387. traverse_obj(videodetails, paths[var_name][1], get_all=False)
  388. or traverse_obj(metadata, paths[var_name][2], get_all=False)
  389. or traverse_obj(renderers,
  390. self._owner_endpoints_path() + paths[var_name][3],
  391. get_all=False)
  392. )
  393. return result or traverse_obj(
  394. extract_attributes(self._search_regex(
  395. r'''(?s)(<link\b[^>]+\bitemprop\s*=\s*("|')%s\2[^>]*>)'''
  396. % re.escape(var_name),
  397. get_element_by_attribute('itemprop', 'author', webpage) or '',
  398. 'author link', default='')),
  399. paths[var_name][0])
  400. @staticmethod
  401. def _yt_urljoin(url_or_path):
  402. return urljoin('https://www.youtube.com', url_or_path)
  403. def _extract_uploader_id(self, uploader_url):
  404. return self._search_regex(
  405. r'/(?:(?:channel|user)/|(?=@))([^/?&#]+)', uploader_url or '',
  406. 'uploader id', default=None)
  407. class YoutubeIE(YoutubeBaseInfoExtractor):
  408. IE_DESC = 'YouTube.com'
  409. _INVIDIOUS_SITES = (
  410. # invidious-redirect websites
  411. r'(?:www\.)?redirect\.invidious\.io',
  412. r'(?:(?:www|dev)\.)?invidio\.us',
  413. # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
  414. r'(?:(?:www|no)\.)?invidiou\.sh',
  415. r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
  416. r'(?:www\.)?invidious\.kabi\.tk',
  417. r'(?:www\.)?invidious\.13ad\.de',
  418. r'(?:www\.)?invidious\.mastodon\.host',
  419. r'(?:www\.)?invidious\.zapashcanon\.fr',
  420. r'(?:www\.)?(?:invidious(?:-us)?|piped)\.kavin\.rocks',
  421. r'(?:www\.)?invidious\.tinfoil-hat\.net',
  422. r'(?:www\.)?invidious\.himiko\.cloud',
  423. r'(?:www\.)?invidious\.reallyancient\.tech',
  424. r'(?:www\.)?invidious\.tube',
  425. r'(?:www\.)?invidiou\.site',
  426. r'(?:www\.)?invidious\.site',
  427. r'(?:www\.)?invidious\.xyz',
  428. r'(?:www\.)?invidious\.nixnet\.xyz',
  429. r'(?:www\.)?invidious\.048596\.xyz',
  430. r'(?:www\.)?invidious\.drycat\.fr',
  431. r'(?:www\.)?inv\.skyn3t\.in',
  432. r'(?:www\.)?tube\.poal\.co',
  433. r'(?:www\.)?tube\.connect\.cafe',
  434. r'(?:www\.)?vid\.wxzm\.sx',
  435. r'(?:www\.)?vid\.mint\.lgbt',
  436. r'(?:www\.)?vid\.puffyan\.us',
  437. r'(?:www\.)?yewtu\.be',
  438. r'(?:www\.)?yt\.elukerio\.org',
  439. r'(?:www\.)?yt\.lelux\.fi',
  440. r'(?:www\.)?invidious\.ggc-project\.de',
  441. r'(?:www\.)?yt\.maisputain\.ovh',
  442. r'(?:www\.)?ytprivate\.com',
  443. r'(?:www\.)?invidious\.13ad\.de',
  444. r'(?:www\.)?invidious\.toot\.koeln',
  445. r'(?:www\.)?invidious\.fdn\.fr',
  446. r'(?:www\.)?watch\.nettohikari\.com',
  447. r'(?:www\.)?invidious\.namazso\.eu',
  448. r'(?:www\.)?invidious\.silkky\.cloud',
  449. r'(?:www\.)?invidious\.exonip\.de',
  450. r'(?:www\.)?invidious\.riverside\.rocks',
  451. r'(?:www\.)?invidious\.blamefran\.net',
  452. r'(?:www\.)?invidious\.moomoo\.de',
  453. r'(?:www\.)?ytb\.trom\.tf',
  454. r'(?:www\.)?yt\.cyberhost\.uk',
  455. r'(?:www\.)?kgg2m7yk5aybusll\.onion',
  456. r'(?:www\.)?qklhadlycap4cnod\.onion',
  457. r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
  458. r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
  459. r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
  460. r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
  461. r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
  462. r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
  463. r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
  464. r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
  465. r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
  466. r'(?:www\.)?hpniueoejy4opn7bc4ftgazyqjoeqwlvh2uiku2xqku6zpoa4bf5ruid\.onion',
  467. )
  468. _VALID_URL = r"""(?x)^
  469. (
  470. (?:https?://|//) # http(s):// or protocol-independent URL
  471. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
  472. (?:www\.)?deturl\.com/www\.youtube\.com|
  473. (?:www\.)?pwnyoutube\.com|
  474. (?:www\.)?hooktube\.com|
  475. (?:www\.)?yourepeat\.com|
  476. tube\.majestyc\.net|
  477. %(invidious)s|
  478. youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
  479. (?:.*?\#/)? # handle anchor (#/) redirect urls
  480. (?: # the various things that can precede the ID:
  481. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  482. |shorts/
  483. |(?: # or the v= param in all its forms
  484. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  485. (?:\?|\#!?) # the params delimiter ? or # or #!
  486. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  487. v=
  488. )
  489. ))
  490. |(?:
  491. youtu\.be| # just youtu.be/xxxx
  492. vid\.plus| # or vid.plus/xxxx
  493. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  494. %(invidious)s
  495. )/
  496. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  497. )
  498. )? # all until now is optional -> you can pass the naked ID
  499. (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  500. (?(1).+)? # if we found the ID, everything can follow
  501. $""" % {
  502. 'invidious': '|'.join(_INVIDIOUS_SITES),
  503. }
  504. _PLAYER_INFO_RE = (
  505. r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
  506. 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$',
  507. r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
  508. )
  509. _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
  510. _GEO_BYPASS = False
  511. IE_NAME = 'youtube'
  512. _TESTS = [
  513. {
  514. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  515. 'info_dict': {
  516. 'id': 'BaW_jenozKc',
  517. 'ext': 'mp4',
  518. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  519. 'uploader': 'Philipp Hagemeister',
  520. 'uploader_id': '@PhilippHagemeister',
  521. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@PhilippHagemeister',
  522. 'channel': 'Philipp Hagemeister',
  523. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  524. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  525. 'upload_date': '20121002',
  526. '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 .',
  527. 'categories': ['Science & Technology'],
  528. 'tags': ['youtube-dl'],
  529. 'duration': 10,
  530. 'view_count': int,
  531. 'like_count': int,
  532. 'thumbnail': 'https://i.ytimg.com/vi/BaW_jenozKc/maxresdefault.jpg',
  533. 'start_time': 1,
  534. 'end_time': 9,
  535. },
  536. },
  537. {
  538. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  539. 'note': 'Embed-only video (#1746)',
  540. 'info_dict': {
  541. 'id': 'yZIXLfi8CZQ',
  542. 'ext': 'mp4',
  543. 'upload_date': '20120608',
  544. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  545. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  546. 'uploader': 'SET India',
  547. 'uploader_id': 'setindia',
  548. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
  549. 'age_limit': 18,
  550. },
  551. 'skip': 'Private video',
  552. },
  553. {
  554. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
  555. 'note': 'Use the first video ID in the URL',
  556. 'info_dict': {
  557. 'id': 'BaW_jenozKc',
  558. 'ext': 'mp4',
  559. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  560. 'uploader': 'Philipp Hagemeister',
  561. 'uploader_id': '@PhilippHagemeister',
  562. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@PhilippHagemeister',
  563. 'upload_date': '20121002',
  564. '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 .',
  565. 'categories': ['Science & Technology'],
  566. 'tags': ['youtube-dl'],
  567. 'duration': 10,
  568. 'view_count': int,
  569. 'like_count': int,
  570. },
  571. 'params': {
  572. 'skip_download': True,
  573. },
  574. },
  575. {
  576. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  577. 'note': '256k DASH audio (format 141) via DASH manifest',
  578. 'info_dict': {
  579. 'id': 'a9LDPn-MO4I',
  580. 'ext': 'm4a',
  581. 'upload_date': '20121002',
  582. 'uploader_id': '8KVIDEO',
  583. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  584. 'description': '',
  585. 'uploader': '8KVIDEO',
  586. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  587. },
  588. 'params': {
  589. 'youtube_include_dash_manifest': True,
  590. 'format': '141',
  591. },
  592. 'skip': 'format 141 not served any more',
  593. },
  594. # DASH manifest with encrypted signature
  595. {
  596. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  597. 'info_dict': {
  598. 'id': 'IB3lcPjvWLA',
  599. 'ext': 'm4a',
  600. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  601. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  602. 'duration': 244,
  603. 'uploader': 'AfrojackVEVO',
  604. 'uploader_id': '@AfrojackVEVO',
  605. 'upload_date': '20131011',
  606. 'abr': 129.495,
  607. },
  608. 'params': {
  609. 'youtube_include_dash_manifest': True,
  610. 'format': '141/bestaudio[ext=m4a]',
  611. },
  612. },
  613. # Controversy video
  614. {
  615. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  616. 'info_dict': {
  617. 'id': 'T4XJQO3qol8',
  618. 'ext': 'mp4',
  619. 'duration': 219,
  620. 'upload_date': '20100909',
  621. 'uploader': 'Amazing Atheist',
  622. 'uploader_id': '@theamazingatheist',
  623. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@theamazingatheist',
  624. 'title': 'Burning Everyone\'s Koran',
  625. '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',
  626. }
  627. },
  628. # Age-gated videos
  629. {
  630. 'note': 'Age-gated video (No vevo, embed allowed)',
  631. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  632. 'info_dict': {
  633. 'id': 'HtVdAasjOgU',
  634. 'ext': 'mp4',
  635. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  636. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  637. 'duration': 142,
  638. 'uploader': 'The Witcher',
  639. 'uploader_id': '@thewitcher',
  640. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@thewitcher',
  641. 'upload_date': '20140605',
  642. 'thumbnail': 'https://i.ytimg.com/vi/HtVdAasjOgU/maxresdefault.jpg',
  643. 'age_limit': 18,
  644. 'categories': ['Gaming'],
  645. 'tags': 'count:17',
  646. 'channel': 'The Witcher',
  647. 'channel_url': 'https://www.youtube.com/channel/UCzybXLxv08IApdjdN0mJhEg',
  648. 'channel_id': 'UCzybXLxv08IApdjdN0mJhEg',
  649. 'view_count': int,
  650. 'like_count': int,
  651. },
  652. },
  653. {
  654. 'note': 'Age-gated video with embed allowed in public site',
  655. 'url': 'https://youtube.com/watch?v=HsUATh_Nc2U',
  656. 'info_dict': {
  657. 'id': 'HsUATh_Nc2U',
  658. 'ext': 'mp4',
  659. 'title': 'Godzilla 2 (Official Video)',
  660. 'description': 'md5:bf77e03fcae5529475e500129b05668a',
  661. 'duration': 177,
  662. 'uploader': 'FlyingKitty',
  663. 'uploader_id': '@FlyingKitty900',
  664. 'upload_date': '20200408',
  665. 'thumbnail': 'https://i.ytimg.com/vi/HsUATh_Nc2U/maxresdefault.jpg',
  666. 'age_limit': 18,
  667. 'categories': ['Entertainment'],
  668. 'tags': ['Flyingkitty', 'godzilla 2'],
  669. 'channel': 'FlyingKitty',
  670. 'channel_url': 'https://www.youtube.com/channel/UCYQT13AtrJC0gsM1far_zJg',
  671. 'channel_id': 'UCYQT13AtrJC0gsM1far_zJg',
  672. 'view_count': int,
  673. 'like_count': int,
  674. },
  675. },
  676. {
  677. 'note': 'Age-gated video embeddable only with clientScreen=EMBED',
  678. 'url': 'https://youtube.com/watch?v=Tq92D6wQ1mg',
  679. 'info_dict': {
  680. 'id': 'Tq92D6wQ1mg',
  681. 'ext': 'mp4',
  682. 'title': '[MMD] Adios - EVERGLOW [+Motion DL]',
  683. 'description': 'md5:17eccca93a786d51bc67646756894066',
  684. 'duration': 106,
  685. 'uploader': 'Projekt Melody',
  686. 'uploader_id': '@ProjektMelody',
  687. 'upload_date': '20191227',
  688. 'age_limit': 18,
  689. 'thumbnail': 'https://i.ytimg.com/vi/Tq92D6wQ1mg/sddefault.jpg',
  690. 'tags': ['mmd', 'dance', 'mikumikudance', 'kpop', 'vtuber'],
  691. 'categories': ['Entertainment'],
  692. 'channel': 'Projekt Melody',
  693. 'channel_url': 'https://www.youtube.com/channel/UC1yoRdFoFJaCY-AGfD9W0wQ',
  694. 'channel_id': 'UC1yoRdFoFJaCY-AGfD9W0wQ',
  695. 'view_count': int,
  696. 'like_count': int,
  697. },
  698. },
  699. {
  700. 'note': 'Non-Age-gated non-embeddable video',
  701. 'url': 'https://youtube.com/watch?v=MeJVWBSsPAY',
  702. 'info_dict': {
  703. 'id': 'MeJVWBSsPAY',
  704. 'ext': 'mp4',
  705. 'title': 'OOMPH! - Such Mich Find Mich (Lyrics)',
  706. 'description': 'Fan Video. Music & Lyrics by OOMPH!.',
  707. 'duration': 210,
  708. 'upload_date': '20130730',
  709. 'uploader': 'Herr Lurik',
  710. 'uploader_id': '@HerrLurik',
  711. 'uploader_url': 'http://www.youtube.com/@HerrLurik',
  712. 'age_limit': 0,
  713. 'thumbnail': 'https://i.ytimg.com/vi/MeJVWBSsPAY/hqdefault.jpg',
  714. 'tags': ['oomph', 'such mich find mich', 'lyrics', 'german industrial', 'musica industrial'],
  715. 'categories': ['Music'],
  716. 'channel': 'Herr Lurik',
  717. 'channel_url': 'https://www.youtube.com/channel/UCdR3RSDPqub28LjZx0v9-aA',
  718. 'channel_id': 'UCdR3RSDPqub28LjZx0v9-aA',
  719. 'artist': 'OOMPH!',
  720. 'view_count': int,
  721. 'like_count': int,
  722. },
  723. },
  724. {
  725. 'note': 'Non-bypassable age-gated video',
  726. 'url': 'https://youtube.com/watch?v=Cr381pDsSsA',
  727. 'only_matching': True,
  728. },
  729. {
  730. 'note': 'Age-gated video only available with authentication (not via embed workaround)',
  731. 'url': 'XgnwCQzjau8',
  732. 'only_matching': True,
  733. 'skip': '''This video has been removed for violating YouTube's Community Guidelines''',
  734. },
  735. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  736. # YouTube Red ad is not captured for creator
  737. {
  738. 'url': '__2ABJjxzNo',
  739. 'info_dict': {
  740. 'id': '__2ABJjxzNo',
  741. 'ext': 'mp4',
  742. 'duration': 266,
  743. 'upload_date': '20100430',
  744. 'uploader_id': '@deadmau5',
  745. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@deadmau5',
  746. 'creator': 'deadmau5',
  747. 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
  748. 'uploader': 'deadmau5',
  749. 'title': 'Deadmau5 - Some Chords (HD)',
  750. 'alt_title': 'Some Chords',
  751. },
  752. 'expected_warnings': [
  753. 'DASH manifest missing',
  754. ]
  755. },
  756. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  757. {
  758. 'url': 'lqQg6PlCWgI',
  759. 'info_dict': {
  760. 'id': 'lqQg6PlCWgI',
  761. 'ext': 'mp4',
  762. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  763. 'description': r're:(?s)(?:.+\s)?HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games\s*',
  764. 'duration': 6085,
  765. 'upload_date': '20150827',
  766. 'uploader_id': '@Olympics',
  767. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@Olympics',
  768. 'uploader': r're:Olympics?',
  769. 'age_limit': 0,
  770. 'thumbnail': 'https://i.ytimg.com/vi/lqQg6PlCWgI/maxresdefault.jpg',
  771. 'categories': ['Sports'],
  772. 'tags': ['Hockey', '2012-07-31', '31 July 2012', 'Riverbank Arena', 'Session', 'Olympics', 'Olympic Games', 'London 2012', '2012 Summer Olympics', 'Summer Games'],
  773. 'channel': 'Olympics',
  774. 'channel_url': 'https://www.youtube.com/channel/UCTl3QQTvqHFjurroKxexy2Q',
  775. 'channel_id': 'UCTl3QQTvqHFjurroKxexy2Q',
  776. 'view_count': int,
  777. 'like_count': int,
  778. },
  779. },
  780. # Non-square pixels
  781. {
  782. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  783. 'info_dict': {
  784. 'id': '_b-2C3KPAM0',
  785. 'ext': 'mp4',
  786. 'stretched_ratio': 16 / 9.,
  787. 'duration': 85,
  788. 'upload_date': '20110310',
  789. 'uploader_id': '@AllenMeow',
  790. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@AllenMeow',
  791. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  792. 'uploader': '孫ᄋᄅ',
  793. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  794. },
  795. },
  796. # url_encoded_fmt_stream_map is empty string
  797. {
  798. 'url': 'qEJwOuvDf7I',
  799. 'info_dict': {
  800. 'id': 'qEJwOuvDf7I',
  801. 'ext': 'webm',
  802. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  803. 'description': '',
  804. 'upload_date': '20150404',
  805. 'uploader_id': 'spbelect',
  806. 'uploader': 'Наблюдатели Петербурга',
  807. },
  808. 'params': {
  809. 'skip_download': 'requires avconv',
  810. },
  811. 'skip': 'This live event has ended.',
  812. },
  813. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  814. {
  815. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  816. 'info_dict': {
  817. 'id': 'FIl7x6_3R5Y',
  818. 'ext': 'webm',
  819. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  820. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  821. 'duration': 220,
  822. 'upload_date': '20150625',
  823. 'uploader_id': 'dorappi2000',
  824. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  825. 'uploader': 'dorappi2000',
  826. 'formats': 'mincount:31',
  827. },
  828. 'skip': 'not actual any more',
  829. },
  830. # DASH manifest with segment_list
  831. {
  832. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  833. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  834. 'info_dict': {
  835. 'id': 'CsmdDsKjzN8',
  836. 'ext': 'mp4',
  837. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  838. 'uploader': 'Airtek',
  839. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  840. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  841. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  842. },
  843. 'params': {
  844. 'youtube_include_dash_manifest': True,
  845. 'format': '135', # bestvideo
  846. },
  847. 'skip': 'This live event has ended.',
  848. },
  849. {
  850. # Multifeed videos (multiple cameras), URL is for Main Camera
  851. 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
  852. 'info_dict': {
  853. 'id': 'jvGDaLqkpTg',
  854. 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
  855. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  856. },
  857. 'playlist': [{
  858. 'info_dict': {
  859. 'id': 'jvGDaLqkpTg',
  860. 'ext': 'mp4',
  861. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
  862. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  863. 'duration': 10643,
  864. 'upload_date': '20161111',
  865. 'uploader': 'Team PGP',
  866. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  867. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  868. },
  869. }, {
  870. 'info_dict': {
  871. 'id': '3AKt1R1aDnw',
  872. 'ext': 'mp4',
  873. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
  874. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  875. 'duration': 10991,
  876. 'upload_date': '20161111',
  877. 'uploader': 'Team PGP',
  878. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  879. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  880. },
  881. }, {
  882. 'info_dict': {
  883. 'id': 'RtAMM00gpVc',
  884. 'ext': 'mp4',
  885. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
  886. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  887. 'duration': 10995,
  888. 'upload_date': '20161111',
  889. 'uploader': 'Team PGP',
  890. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  891. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  892. },
  893. }, {
  894. 'info_dict': {
  895. 'id': '6N2fdlP3C5U',
  896. 'ext': 'mp4',
  897. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
  898. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  899. 'duration': 10990,
  900. 'upload_date': '20161111',
  901. 'uploader': 'Team PGP',
  902. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  903. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  904. },
  905. }],
  906. 'params': {
  907. 'skip_download': True,
  908. },
  909. 'skip': 'Not multifeed any more',
  910. },
  911. {
  912. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  913. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  914. 'info_dict': {
  915. 'id': 'gVfLd0zydlo',
  916. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  917. },
  918. 'playlist_count': 2,
  919. 'skip': 'Not multifeed any more',
  920. },
  921. {
  922. 'url': 'https://vid.plus/FlRa-iH7PGw',
  923. 'only_matching': True,
  924. },
  925. {
  926. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  927. 'only_matching': True,
  928. },
  929. {
  930. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  931. # Also tests cut-off URL expansion in video description (see
  932. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  933. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  934. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  935. 'info_dict': {
  936. 'id': 'lsguqyKfVQg',
  937. 'ext': 'mp4',
  938. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  939. 'alt_title': 'Dark Walk',
  940. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  941. 'duration': 133,
  942. 'upload_date': '20151119',
  943. 'uploader_id': '@IronSoulElf',
  944. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@IronSoulElf',
  945. 'uploader': 'IronSoulElf',
  946. 'creator': r're:Todd Haberman[;,]\s+Daniel Law Heath and Aaron Kaplan',
  947. 'track': 'Dark Walk',
  948. 'artist': r're:Todd Haberman[;,]\s+Daniel Law Heath and Aaron Kaplan',
  949. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  950. },
  951. 'params': {
  952. 'skip_download': True,
  953. },
  954. },
  955. {
  956. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  957. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  958. 'only_matching': True,
  959. },
  960. {
  961. # Video with yt:stretch=17:0
  962. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  963. 'info_dict': {
  964. 'id': 'Q39EVAstoRM',
  965. 'ext': 'mp4',
  966. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  967. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  968. 'upload_date': '20151107',
  969. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  970. 'uploader': 'CH GAMER DROID',
  971. },
  972. 'params': {
  973. 'skip_download': True,
  974. },
  975. 'skip': 'This video does not exist.',
  976. },
  977. {
  978. # Video with incomplete 'yt:stretch=16:'
  979. 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
  980. 'only_matching': True,
  981. },
  982. {
  983. # Video licensed under Creative Commons
  984. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  985. 'info_dict': {
  986. 'id': 'M4gD1WSo5mA',
  987. 'ext': 'mp4',
  988. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  989. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  990. 'duration': 721,
  991. 'upload_date': '20150127',
  992. 'uploader_id': '@BKCHarvard',
  993. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@BKCHarvard',
  994. 'uploader': 'The Berkman Klein Center for Internet & Society',
  995. 'license': 'Creative Commons Attribution license (reuse allowed)',
  996. },
  997. 'params': {
  998. 'skip_download': True,
  999. },
  1000. },
  1001. {
  1002. # Channel-like uploader_url
  1003. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  1004. 'info_dict': {
  1005. 'id': 'eQcmzGIKrzg',
  1006. 'ext': 'mp4',
  1007. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  1008. 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
  1009. 'duration': 4060,
  1010. 'upload_date': '20151119',
  1011. 'uploader': 'Bernie Sanders',
  1012. 'uploader_id': '@BernieSanders',
  1013. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@BernieSanders',
  1014. 'license': 'Creative Commons Attribution license (reuse allowed)',
  1015. },
  1016. 'params': {
  1017. 'skip_download': True,
  1018. },
  1019. },
  1020. {
  1021. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  1022. 'only_matching': True,
  1023. },
  1024. {
  1025. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  1026. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  1027. 'only_matching': True,
  1028. },
  1029. {
  1030. # Rental video preview
  1031. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  1032. 'info_dict': {
  1033. 'id': 'uGpuVWrhIzE',
  1034. 'ext': 'mp4',
  1035. 'title': 'Piku - Trailer',
  1036. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  1037. 'upload_date': '20150811',
  1038. 'uploader': 'FlixMatrix',
  1039. 'uploader_id': 'FlixMatrixKaravan',
  1040. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
  1041. 'license': 'Standard YouTube License',
  1042. },
  1043. 'params': {
  1044. 'skip_download': True,
  1045. },
  1046. 'skip': 'This video is not available.',
  1047. },
  1048. {
  1049. # YouTube Red video with episode data
  1050. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  1051. 'info_dict': {
  1052. 'id': 'iqKdEhx-dD4',
  1053. 'ext': 'mp4',
  1054. 'title': 'Isolation - Mind Field (Ep 1)',
  1055. 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
  1056. 'duration': 2085,
  1057. 'upload_date': '20170118',
  1058. 'uploader': 'Vsauce',
  1059. 'uploader_id': '@Vsauce',
  1060. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@Vsauce',
  1061. 'series': 'Mind Field',
  1062. 'season_number': 1,
  1063. 'episode_number': 1,
  1064. },
  1065. 'params': {
  1066. 'skip_download': True,
  1067. },
  1068. 'expected_warnings': [
  1069. 'Skipping DASH manifest',
  1070. ],
  1071. },
  1072. {
  1073. # The following content has been identified by the YouTube community
  1074. # as inappropriate or offensive to some audiences.
  1075. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  1076. 'info_dict': {
  1077. 'id': '6SJNVb0GnPI',
  1078. 'ext': 'mp4',
  1079. 'title': 'Race Differences in Intelligence',
  1080. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  1081. 'duration': 965,
  1082. 'upload_date': '20140124',
  1083. 'uploader': 'New Century Foundation',
  1084. 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
  1085. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
  1086. },
  1087. 'params': {
  1088. 'skip_download': True,
  1089. },
  1090. 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
  1091. },
  1092. {
  1093. # itag 212
  1094. 'url': '1t24XAntNCY',
  1095. 'only_matching': True,
  1096. },
  1097. {
  1098. # geo restricted to JP
  1099. 'url': 'sJL6WA-aGkQ',
  1100. 'only_matching': True,
  1101. },
  1102. {
  1103. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  1104. 'only_matching': True,
  1105. },
  1106. {
  1107. 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
  1108. 'only_matching': True,
  1109. },
  1110. {
  1111. # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
  1112. 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
  1113. 'only_matching': True,
  1114. },
  1115. {
  1116. # DRM protected
  1117. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  1118. 'only_matching': True,
  1119. },
  1120. {
  1121. # Video with unsupported adaptive stream type formats
  1122. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  1123. 'info_dict': {
  1124. 'id': 'Z4Vy8R84T1U',
  1125. 'ext': 'mp4',
  1126. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  1127. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  1128. 'duration': 433,
  1129. 'upload_date': '20130923',
  1130. 'uploader': 'Amelia Putri Harwita',
  1131. 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
  1132. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
  1133. 'formats': 'maxcount:10',
  1134. },
  1135. 'params': {
  1136. 'skip_download': True,
  1137. 'youtube_include_dash_manifest': False,
  1138. },
  1139. 'skip': 'not actual any more',
  1140. },
  1141. {
  1142. # Youtube Music Auto-generated description
  1143. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  1144. 'info_dict': {
  1145. 'id': 'MgNrAu2pzNs',
  1146. 'ext': 'mp4',
  1147. 'title': 'Voyeur Girl',
  1148. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  1149. 'upload_date': '20190312',
  1150. 'uploader': 'Stephen - Topic',
  1151. 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
  1152. 'artist': 'Stephen',
  1153. 'track': 'Voyeur Girl',
  1154. 'album': 'it\'s too much love to know my dear',
  1155. 'release_date': '20190313',
  1156. 'release_year': 2019,
  1157. },
  1158. 'params': {
  1159. 'skip_download': True,
  1160. },
  1161. },
  1162. {
  1163. 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
  1164. 'only_matching': True,
  1165. },
  1166. {
  1167. # invalid -> valid video id redirection
  1168. 'url': 'DJztXj2GPfl',
  1169. 'info_dict': {
  1170. 'id': 'DJztXj2GPfk',
  1171. 'ext': 'mp4',
  1172. 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
  1173. 'description': 'md5:bf577a41da97918e94fa9798d9228825',
  1174. 'upload_date': '20090125',
  1175. 'uploader': 'Prochorowka',
  1176. 'uploader_id': 'Prochorowka',
  1177. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
  1178. 'artist': 'Panjabi MC',
  1179. 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
  1180. 'album': 'Beware of the Boys (Mundian To Bach Ke)',
  1181. },
  1182. 'params': {
  1183. 'skip_download': True,
  1184. },
  1185. 'skip': 'Video unavailable',
  1186. },
  1187. {
  1188. # empty description results in an empty string
  1189. 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
  1190. 'info_dict': {
  1191. 'id': 'x41yOUIvK2k',
  1192. 'ext': 'mp4',
  1193. 'title': 'IMG 3456',
  1194. 'description': '',
  1195. 'upload_date': '20170613',
  1196. 'uploader': 'ElevageOrVert',
  1197. 'uploader_id': '@ElevageOrVert',
  1198. },
  1199. 'params': {
  1200. 'skip_download': True,
  1201. },
  1202. },
  1203. {
  1204. # with '};' inside yt initial data (see [1])
  1205. # see [2] for an example with '};' inside ytInitialPlayerResponse
  1206. # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
  1207. # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
  1208. 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
  1209. 'info_dict': {
  1210. 'id': 'CHqg6qOn4no',
  1211. 'ext': 'mp4',
  1212. 'title': 'Part 77 Sort a list of simple types in c#',
  1213. 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
  1214. 'upload_date': '20130831',
  1215. 'uploader': 'kudvenkat',
  1216. 'uploader_id': '@Csharp-video-tutorialsBlogspot',
  1217. },
  1218. 'params': {
  1219. 'skip_download': True,
  1220. },
  1221. },
  1222. {
  1223. # another example of '};' in ytInitialData
  1224. 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
  1225. 'only_matching': True,
  1226. },
  1227. {
  1228. 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
  1229. 'only_matching': True,
  1230. },
  1231. {
  1232. # https://github.com/ytdl-org/youtube-dl/pull/28094
  1233. 'url': 'OtqTfy26tG0',
  1234. 'info_dict': {
  1235. 'id': 'OtqTfy26tG0',
  1236. 'ext': 'mp4',
  1237. 'title': 'Burn Out',
  1238. 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
  1239. 'upload_date': '20141120',
  1240. 'uploader': 'The Cinematic Orchestra - Topic',
  1241. 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
  1242. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
  1243. 'artist': 'The Cinematic Orchestra',
  1244. 'track': 'Burn Out',
  1245. 'album': 'Every Day',
  1246. 'release_data': None,
  1247. 'release_year': None,
  1248. },
  1249. 'params': {
  1250. 'skip_download': True,
  1251. },
  1252. },
  1253. {
  1254. # controversial video, only works with bpctr when authenticated with cookies
  1255. 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
  1256. 'only_matching': True,
  1257. },
  1258. {
  1259. # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
  1260. 'url': 'cBvYw8_A0vQ',
  1261. 'info_dict': {
  1262. 'id': 'cBvYw8_A0vQ',
  1263. 'ext': 'mp4',
  1264. 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
  1265. 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
  1266. 'upload_date': '20201120',
  1267. 'uploader': 'Walk around Japan',
  1268. 'uploader_id': '@walkaroundjapan7124',
  1269. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@walkaroundjapan7124',
  1270. },
  1271. 'params': {
  1272. 'skip_download': True,
  1273. },
  1274. },
  1275. {
  1276. # YT 'Shorts'
  1277. 'url': 'https://youtube.com/shorts/4L2J27mJ3Dc',
  1278. 'info_dict': {
  1279. 'id': '4L2J27mJ3Dc',
  1280. 'ext': 'mp4',
  1281. 'title': 'Midwest Squid Game #Shorts',
  1282. 'description': 'md5:976512b8a29269b93bbd8a61edc45a6d',
  1283. 'upload_date': '20211025',
  1284. 'uploader': 'Charlie Berens',
  1285. 'uploader_id': '@CharlieBerens',
  1286. },
  1287. 'params': {
  1288. 'skip_download': True,
  1289. },
  1290. },
  1291. ]
  1292. _formats = {
  1293. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1294. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1295. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  1296. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  1297. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  1298. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1299. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1300. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1301. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  1302. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  1303. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1304. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1305. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1306. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1307. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1308. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1309. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1310. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1311. # 3D videos
  1312. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1313. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1314. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1315. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1316. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  1317. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1318. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1319. # Apple HTTP Live Streaming
  1320. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1321. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1322. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1323. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1324. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1325. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1326. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1327. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  1328. # DASH mp4 video
  1329. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1330. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1331. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1332. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1333. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1334. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  1335. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1336. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1337. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1338. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1339. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1340. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1341. # Dash mp4 audio
  1342. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  1343. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  1344. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  1345. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1346. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1347. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  1348. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  1349. # Dash webm
  1350. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1351. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1352. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1353. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1354. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1355. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1356. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  1357. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1358. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1359. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1360. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1361. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1362. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1363. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1364. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1365. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  1366. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1367. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1368. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1369. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1370. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1371. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1372. # Dash webm audio
  1373. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  1374. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  1375. # Dash webm audio with opus inside
  1376. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  1377. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  1378. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  1379. # RTMP (unnamed)
  1380. '_rtmp': {'protocol': 'rtmp'},
  1381. # av01 video only formats sometimes served with "unknown" codecs
  1382. '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1383. '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1384. '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1385. '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1386. }
  1387. @classmethod
  1388. def suitable(cls, url):
  1389. if parse_qs(url).get('list', [None])[0]:
  1390. return False
  1391. return super(YoutubeIE, cls).suitable(url)
  1392. def __init__(self, *args, **kwargs):
  1393. super(YoutubeIE, self).__init__(*args, **kwargs)
  1394. self._code_cache = {}
  1395. self._player_cache = {}
  1396. def _signature_cache_id(self, example_sig):
  1397. """ Return a string representation of a signature """
  1398. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  1399. @classmethod
  1400. def _extract_player_info(cls, player_url):
  1401. for player_re in cls._PLAYER_INFO_RE:
  1402. id_m = re.search(player_re, player_url)
  1403. if id_m:
  1404. break
  1405. else:
  1406. raise ExtractorError('Cannot identify player %r' % player_url)
  1407. return id_m.group('id')
  1408. def _get_player_code(self, video_id, player_url, player_id=None):
  1409. if not player_id:
  1410. player_id = self._extract_player_info(player_url)
  1411. if player_id not in self._code_cache:
  1412. self._code_cache[player_id] = self._download_webpage(
  1413. player_url, video_id,
  1414. note='Downloading player ' + player_id,
  1415. errnote='Download of %s failed' % player_url)
  1416. return self._code_cache[player_id]
  1417. def _extract_signature_function(self, video_id, player_url, example_sig):
  1418. player_id = self._extract_player_info(player_url)
  1419. # Read from filesystem cache
  1420. func_id = 'js_%s_%s' % (
  1421. player_id, self._signature_cache_id(example_sig))
  1422. assert os.path.basename(func_id) == func_id
  1423. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  1424. if cache_spec is not None:
  1425. return lambda s: ''.join(s[i] for i in cache_spec)
  1426. code = self._get_player_code(video_id, player_url, player_id)
  1427. res = self._parse_sig_js(code)
  1428. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1429. cache_res = res(test_string)
  1430. cache_spec = [ord(c) for c in cache_res]
  1431. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  1432. return res
  1433. def _print_sig_code(self, func, example_sig):
  1434. def gen_sig_code(idxs):
  1435. def _genslice(start, end, step):
  1436. starts = '' if start == 0 else str(start)
  1437. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  1438. steps = '' if step == 1 else (':%d' % step)
  1439. return 's[%s%s%s]' % (starts, ends, steps)
  1440. step = None
  1441. # Quelch pyflakes warnings - start will be set when step is set
  1442. start = '(Never used)'
  1443. for i, prev in zip(idxs[1:], idxs[:-1]):
  1444. if step is not None:
  1445. if i - prev == step:
  1446. continue
  1447. yield _genslice(start, prev, step)
  1448. step = None
  1449. continue
  1450. if i - prev in [-1, 1]:
  1451. step = i - prev
  1452. start = prev
  1453. continue
  1454. else:
  1455. yield 's[%d]' % prev
  1456. if step is None:
  1457. yield 's[%d]' % i
  1458. else:
  1459. yield _genslice(start, i, step)
  1460. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1461. cache_res = func(test_string)
  1462. cache_spec = [ord(c) for c in cache_res]
  1463. expr_code = ' + '.join(gen_sig_code(cache_spec))
  1464. signature_id_tuple = '(%s)' % (
  1465. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  1466. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  1467. ' return %s\n') % (signature_id_tuple, expr_code)
  1468. self.to_screen('Extracted signature function:\n' + code)
  1469. def _parse_sig_js(self, jscode):
  1470. funcname = self._search_regex(
  1471. (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1472. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1473. r'\bm=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(h\.s\)\)',
  1474. r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(c\)\)',
  1475. 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+\)',
  1476. r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1477. r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1478. # Obsolete patterns
  1479. r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1480. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1481. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1482. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1483. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1484. r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1485. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\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. 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2448. 'only_matching': True,
  2449. }, {
  2450. 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2451. 'only_matching': True,
  2452. }, {
  2453. 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2454. 'only_matching': True,
  2455. }, {
  2456. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2457. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2458. 'info_dict': {
  2459. 'title': '29C3: Not my department',
  2460. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2461. 'uploader': 'Christiaan008',
  2462. 'uploader_id': '@ChRiStIaAn008',
  2463. 'channel_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
  2464. },
  2465. 'playlist_count': 96,
  2466. }, {
  2467. 'note': 'Large playlist',
  2468. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2469. 'info_dict': {
  2470. 'title': 'Uploads from Cauchemar',
  2471. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2472. 'uploader': 'Cauchemar',
  2473. 'uploader_id': '@Cauchemar89',
  2474. 'channel_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
  2475. },
  2476. 'playlist_mincount': 1123,
  2477. }, {
  2478. # even larger playlist, 8832 videos
  2479. 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
  2480. 'only_matching': True,
  2481. }, {
  2482. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2483. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2484. 'info_dict': {
  2485. 'title': 'Uploads from Interstellar Movie',
  2486. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2487. 'uploader': 'Interstellar Movie',
  2488. 'uploader_id': '@InterstellarMovie',
  2489. 'channel_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
  2490. },
  2491. 'playlist_mincount': 21,
  2492. }, {
  2493. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2494. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2495. 'info_dict': {
  2496. 'title': 'Data Analysis with Dr Mike Pound',
  2497. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2498. 'uploader': 'Computerphile',
  2499. 'uploader_id': '@Computerphile',
  2500. 'channel_id': 'UC9-y-6csu5WGm29I7JiwpnA',
  2501. },
  2502. 'playlist_mincount': 11,
  2503. }, {
  2504. 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2505. 'only_matching': True,
  2506. }, {
  2507. # Playlist URL that does not actually serve a playlist
  2508. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2509. 'info_dict': {
  2510. 'id': 'FqZTN594JQw',
  2511. 'ext': 'webm',
  2512. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2513. 'uploader': 'STREEM',
  2514. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2515. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2516. 'upload_date': '20150526',
  2517. 'license': 'Standard YouTube License',
  2518. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2519. 'categories': ['People & Blogs'],
  2520. 'tags': list,
  2521. 'view_count': int,
  2522. 'like_count': int,
  2523. },
  2524. 'params': {
  2525. 'skip_download': True,
  2526. },
  2527. 'skip': 'This video is not available.',
  2528. 'add_ie': [YoutubeIE.ie_key()],
  2529. }, {
  2530. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  2531. 'only_matching': True,
  2532. }, {
  2533. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  2534. 'only_matching': True,
  2535. }, {
  2536. 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
  2537. 'info_dict': {
  2538. 'id': r're:[\da-zA-Z_-]{8,}',
  2539. 'ext': 'mp4',
  2540. 'title': r're:(?s)[A-Z].{20,}',
  2541. 'uploader': 'Sky News',
  2542. 'uploader_id': '@SkyNews',
  2543. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@SkyNews',
  2544. 'upload_date': r're:\d{8}',
  2545. 'description': r're:(?s)(?:.*\n)+SUBSCRIBE to our YouTube channel for more videos: http://www\.youtube\.com/skynews *\n.*',
  2546. 'categories': ['News & Politics'],
  2547. 'tags': list,
  2548. 'like_count': int,
  2549. },
  2550. 'params': {
  2551. 'skip_download': True,
  2552. },
  2553. }, {
  2554. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2555. 'info_dict': {
  2556. 'id': 'a48o2S1cPoo',
  2557. 'ext': 'mp4',
  2558. 'title': 'The Young Turks - Live Main Show',
  2559. 'uploader': 'The Young Turks',
  2560. 'uploader_id': 'TheYoungTurks',
  2561. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2562. 'upload_date': '20150715',
  2563. 'license': 'Standard YouTube License',
  2564. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2565. 'categories': ['News & Politics'],
  2566. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2567. 'like_count': int,
  2568. },
  2569. 'params': {
  2570. 'skip_download': True,
  2571. },
  2572. 'only_matching': True,
  2573. }, {
  2574. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2575. 'only_matching': True,
  2576. }, {
  2577. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2578. 'only_matching': True,
  2579. }, {
  2580. 'url': 'https://www.youtube.com/feed/trending',
  2581. 'only_matching': True,
  2582. }, {
  2583. # needs auth
  2584. 'url': 'https://www.youtube.com/feed/library',
  2585. 'only_matching': True,
  2586. }, {
  2587. # needs auth
  2588. 'url': 'https://www.youtube.com/feed/history',
  2589. 'only_matching': True,
  2590. }, {
  2591. # needs auth
  2592. 'url': 'https://www.youtube.com/feed/subscriptions',
  2593. 'only_matching': True,
  2594. }, {
  2595. # needs auth
  2596. 'url': 'https://www.youtube.com/feed/watch_later',
  2597. 'only_matching': True,
  2598. }, {
  2599. # no longer available?
  2600. 'url': 'https://www.youtube.com/feed/recommended',
  2601. 'only_matching': True,
  2602. }, {
  2603. # inline playlist with not always working continuations
  2604. 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
  2605. 'only_matching': True,
  2606. }, {
  2607. 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
  2608. 'only_matching': True,
  2609. }, {
  2610. 'url': 'https://www.youtube.com/course',
  2611. 'only_matching': True,
  2612. }, {
  2613. 'url': 'https://www.youtube.com/zsecurity',
  2614. 'only_matching': True,
  2615. }, {
  2616. 'url': 'http://www.youtube.com/NASAgovVideo/videos',
  2617. 'only_matching': True,
  2618. }, {
  2619. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2620. 'only_matching': True,
  2621. }, {
  2622. 'url': 'https://www.youtube.com/hashtag/cctv9',
  2623. 'info_dict': {
  2624. 'id': 'cctv9',
  2625. 'title': '#cctv9',
  2626. },
  2627. 'playlist_mincount': 350,
  2628. }, {
  2629. 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
  2630. 'only_matching': True,
  2631. }, {
  2632. 'note': 'Search tab',
  2633. 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
  2634. 'playlist_mincount': 20,
  2635. 'info_dict': {
  2636. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  2637. 'title': '3Blue1Brown - Search - linear algebra',
  2638. 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
  2639. 'uploader': '3Blue1Brown',
  2640. 'uploader_id': '@3blue1brown',
  2641. 'channel_id': 'UCYO_jab_esuFRV4b17AJtAw',
  2642. }
  2643. }]
  2644. @classmethod
  2645. def suitable(cls, url):
  2646. return not YoutubeIE.suitable(url) and super(
  2647. YoutubeTabIE, cls).suitable(url)
  2648. @staticmethod
  2649. def _extract_grid_item_renderer(item):
  2650. assert isinstance(item, dict)
  2651. for key, renderer in item.items():
  2652. if not key.startswith('grid') or not key.endswith('Renderer'):
  2653. continue
  2654. if not isinstance(renderer, dict):
  2655. continue
  2656. return renderer
  2657. def _grid_entries(self, grid_renderer):
  2658. for item in grid_renderer['items']:
  2659. if not isinstance(item, dict):
  2660. continue
  2661. renderer = self._extract_grid_item_renderer(item)
  2662. if not isinstance(renderer, dict):
  2663. continue
  2664. title = try_get(
  2665. renderer, (lambda x: x['title']['runs'][0]['text'],
  2666. lambda x: x['title']['simpleText']), compat_str)
  2667. # playlist
  2668. playlist_id = renderer.get('playlistId')
  2669. if playlist_id:
  2670. yield self.url_result(
  2671. 'https://www.youtube.com/playlist?list=%s' % playlist_id,
  2672. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  2673. video_title=title)
  2674. continue
  2675. # video
  2676. video_id = renderer.get('videoId')
  2677. if video_id:
  2678. yield self._extract_video(renderer)
  2679. continue
  2680. # channel
  2681. channel_id = renderer.get('channelId')
  2682. if channel_id:
  2683. title = try_get(
  2684. renderer, lambda x: x['title']['simpleText'], compat_str)
  2685. yield self.url_result(
  2686. 'https://www.youtube.com/channel/%s' % channel_id,
  2687. ie=YoutubeTabIE.ie_key(), video_title=title)
  2688. continue
  2689. # generic endpoint URL support
  2690. ep_url = urljoin('https://www.youtube.com/', try_get(
  2691. renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
  2692. compat_str))
  2693. if ep_url:
  2694. for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
  2695. if ie.suitable(ep_url):
  2696. yield self.url_result(
  2697. ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
  2698. break
  2699. def _shelf_entries_from_content(self, shelf_renderer):
  2700. content = shelf_renderer.get('content')
  2701. if not isinstance(content, dict):
  2702. return
  2703. renderer = content.get('gridRenderer')
  2704. if renderer:
  2705. # TODO: add support for nested playlists so each shelf is processed
  2706. # as separate playlist
  2707. # TODO: this includes only first N items
  2708. for entry in self._grid_entries(renderer):
  2709. yield entry
  2710. renderer = content.get('horizontalListRenderer')
  2711. if renderer:
  2712. # TODO
  2713. pass
  2714. def _shelf_entries(self, shelf_renderer, skip_channels=False):
  2715. ep = try_get(
  2716. shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  2717. compat_str)
  2718. shelf_url = urljoin('https://www.youtube.com', ep)
  2719. if shelf_url:
  2720. # Skipping links to another channels, note that checking for
  2721. # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
  2722. # will not work
  2723. if skip_channels and '/channels?' in shelf_url:
  2724. return
  2725. title = try_get(
  2726. shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
  2727. yield self.url_result(shelf_url, video_title=title)
  2728. # Shelf may not contain shelf URL, fallback to extraction from content
  2729. for entry in self._shelf_entries_from_content(shelf_renderer):
  2730. yield entry
  2731. def _playlist_entries(self, video_list_renderer):
  2732. for content in video_list_renderer['contents']:
  2733. if not isinstance(content, dict):
  2734. continue
  2735. renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
  2736. if not isinstance(renderer, dict):
  2737. continue
  2738. video_id = renderer.get('videoId')
  2739. if not video_id:
  2740. continue
  2741. yield self._extract_video(renderer)
  2742. def _video_entry(self, video_renderer):
  2743. video_id = video_renderer.get('videoId')
  2744. if video_id:
  2745. return self._extract_video(video_renderer)
  2746. def _post_thread_entries(self, post_thread_renderer):
  2747. post_renderer = try_get(
  2748. post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
  2749. if not post_renderer:
  2750. return
  2751. # video attachment
  2752. video_renderer = try_get(
  2753. post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
  2754. video_id = None
  2755. if video_renderer:
  2756. entry = self._video_entry(video_renderer)
  2757. if entry:
  2758. yield entry
  2759. # inline video links
  2760. runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
  2761. for run in runs:
  2762. if not isinstance(run, dict):
  2763. continue
  2764. ep_url = try_get(
  2765. run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
  2766. if not ep_url:
  2767. continue
  2768. if not YoutubeIE.suitable(ep_url):
  2769. continue
  2770. ep_video_id = YoutubeIE._match_id(ep_url)
  2771. if video_id == ep_video_id:
  2772. continue
  2773. yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
  2774. def _post_thread_continuation_entries(self, post_thread_continuation):
  2775. contents = post_thread_continuation.get('contents')
  2776. if not isinstance(contents, list):
  2777. return
  2778. for content in contents:
  2779. renderer = content.get('backstagePostThreadRenderer')
  2780. if not isinstance(renderer, dict):
  2781. continue
  2782. for entry in self._post_thread_entries(renderer):
  2783. yield entry
  2784. def _rich_grid_entries(self, contents):
  2785. for content in contents:
  2786. video_renderer = try_get(
  2787. content,
  2788. (lambda x: x['richItemRenderer']['content']['videoRenderer'],
  2789. lambda x: x['richItemRenderer']['content']['reelItemRenderer']),
  2790. dict)
  2791. if video_renderer:
  2792. entry = self._video_entry(video_renderer)
  2793. if entry:
  2794. yield entry
  2795. @staticmethod
  2796. def _build_continuation_query(continuation, ctp=None):
  2797. query = {
  2798. 'ctoken': continuation,
  2799. 'continuation': continuation,
  2800. }
  2801. if ctp:
  2802. query['itct'] = ctp
  2803. return query
  2804. @staticmethod
  2805. def _extract_next_continuation_data(renderer):
  2806. next_continuation = try_get(
  2807. renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
  2808. if not next_continuation:
  2809. return
  2810. continuation = next_continuation.get('continuation')
  2811. if not continuation:
  2812. return
  2813. ctp = next_continuation.get('clickTrackingParams')
  2814. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  2815. @classmethod
  2816. def _extract_continuation(cls, renderer):
  2817. next_continuation = cls._extract_next_continuation_data(renderer)
  2818. if next_continuation:
  2819. return next_continuation
  2820. contents = []
  2821. for key in ('contents', 'items'):
  2822. contents.extend(try_get(renderer, lambda x: x[key], list) or [])
  2823. for content in contents:
  2824. if not isinstance(content, dict):
  2825. continue
  2826. continuation_ep = try_get(
  2827. content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
  2828. dict)
  2829. if not continuation_ep:
  2830. continue
  2831. continuation = try_get(
  2832. continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
  2833. if not continuation:
  2834. continue
  2835. ctp = continuation_ep.get('clickTrackingParams')
  2836. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  2837. def _entries(self, tab, item_id, webpage):
  2838. tab_content = try_get(tab, lambda x: x['content'], dict)
  2839. if not tab_content:
  2840. return
  2841. slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
  2842. if slr_renderer:
  2843. is_channels_tab = tab.get('title') == 'Channels'
  2844. continuation = None
  2845. slr_contents = try_get(slr_renderer, lambda x: x['contents'], list) or []
  2846. for slr_content in slr_contents:
  2847. if not isinstance(slr_content, dict):
  2848. continue
  2849. is_renderer = try_get(slr_content, lambda x: x['itemSectionRenderer'], dict)
  2850. if not is_renderer:
  2851. continue
  2852. isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
  2853. for isr_content in isr_contents:
  2854. if not isinstance(isr_content, dict):
  2855. continue
  2856. renderer = isr_content.get('playlistVideoListRenderer')
  2857. if renderer:
  2858. for entry in self._playlist_entries(renderer):
  2859. yield entry
  2860. continuation = self._extract_continuation(renderer)
  2861. continue
  2862. renderer = isr_content.get('gridRenderer')
  2863. if renderer:
  2864. for entry in self._grid_entries(renderer):
  2865. yield entry
  2866. continuation = self._extract_continuation(renderer)
  2867. continue
  2868. renderer = isr_content.get('shelfRenderer')
  2869. if renderer:
  2870. for entry in self._shelf_entries(renderer, not is_channels_tab):
  2871. yield entry
  2872. continue
  2873. renderer = isr_content.get('backstagePostThreadRenderer')
  2874. if renderer:
  2875. for entry in self._post_thread_entries(renderer):
  2876. yield entry
  2877. continuation = self._extract_continuation(renderer)
  2878. continue
  2879. renderer = isr_content.get('videoRenderer')
  2880. if renderer:
  2881. entry = self._video_entry(renderer)
  2882. if entry:
  2883. yield entry
  2884. if not continuation:
  2885. continuation = self._extract_continuation(is_renderer)
  2886. if not continuation:
  2887. continuation = self._extract_continuation(slr_renderer)
  2888. else:
  2889. rich_grid_renderer = tab_content.get('richGridRenderer')
  2890. if not rich_grid_renderer:
  2891. return
  2892. for entry in self._rich_grid_entries(rich_grid_renderer.get('contents') or []):
  2893. yield entry
  2894. continuation = self._extract_continuation(rich_grid_renderer)
  2895. ytcfg = self._extract_ytcfg(item_id, webpage)
  2896. client_version = try_get(
  2897. ytcfg, lambda x: x['INNERTUBE_CLIENT_VERSION'], compat_str) or '2.20210407.08.00'
  2898. headers = {
  2899. 'x-youtube-client-name': '1',
  2900. 'x-youtube-client-version': client_version,
  2901. 'content-type': 'application/json',
  2902. }
  2903. context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'], dict) or {
  2904. 'client': {
  2905. 'clientName': 'WEB',
  2906. 'clientVersion': client_version,
  2907. }
  2908. }
  2909. visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
  2910. identity_token = self._extract_identity_token(ytcfg, webpage)
  2911. if identity_token:
  2912. headers['x-youtube-identity-token'] = identity_token
  2913. data = {
  2914. 'context': context,
  2915. }
  2916. for page_num in itertools.count(1):
  2917. if not continuation:
  2918. break
  2919. if visitor_data:
  2920. headers['x-goog-visitor-id'] = visitor_data
  2921. data['continuation'] = continuation['continuation']
  2922. data['clickTracking'] = {
  2923. 'clickTrackingParams': continuation['itct']
  2924. }
  2925. count = 0
  2926. retries = 3
  2927. while count <= retries:
  2928. try:
  2929. # Downloading page may result in intermittent 5xx HTTP error
  2930. # that is usually worked around with a retry
  2931. response = self._download_json(
  2932. 'https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  2933. None, 'Downloading page %d%s' % (page_num, ' (retry #%d)' % count if count else ''),
  2934. headers=headers, data=json.dumps(data).encode('utf8'))
  2935. break
  2936. except ExtractorError as e:
  2937. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  2938. count += 1
  2939. if count <= retries:
  2940. continue
  2941. raise
  2942. if not response:
  2943. break
  2944. visitor_data = try_get(
  2945. response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
  2946. continuation_contents = try_get(
  2947. response, lambda x: x['continuationContents'], dict)
  2948. if continuation_contents:
  2949. continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
  2950. if continuation_renderer:
  2951. for entry in self._playlist_entries(continuation_renderer):
  2952. yield entry
  2953. continuation = self._extract_continuation(continuation_renderer)
  2954. continue
  2955. continuation_renderer = continuation_contents.get('gridContinuation')
  2956. if continuation_renderer:
  2957. for entry in self._grid_entries(continuation_renderer):
  2958. yield entry
  2959. continuation = self._extract_continuation(continuation_renderer)
  2960. continue
  2961. continuation_renderer = continuation_contents.get('itemSectionContinuation')
  2962. if continuation_renderer:
  2963. for entry in self._post_thread_continuation_entries(continuation_renderer):
  2964. yield entry
  2965. continuation = self._extract_continuation(continuation_renderer)
  2966. continue
  2967. on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
  2968. continuation_items = try_get(
  2969. on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
  2970. if continuation_items:
  2971. continuation_item = continuation_items[0]
  2972. if not isinstance(continuation_item, dict):
  2973. continue
  2974. renderer = self._extract_grid_item_renderer(continuation_item)
  2975. if renderer:
  2976. grid_renderer = {'items': continuation_items}
  2977. for entry in self._grid_entries(grid_renderer):
  2978. yield entry
  2979. continuation = self._extract_continuation(grid_renderer)
  2980. continue
  2981. renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
  2982. if renderer:
  2983. video_list_renderer = {'contents': continuation_items}
  2984. for entry in self._playlist_entries(video_list_renderer):
  2985. yield entry
  2986. continuation = self._extract_continuation(video_list_renderer)
  2987. continue
  2988. renderer = continuation_item.get('backstagePostThreadRenderer')
  2989. if renderer:
  2990. continuation_renderer = {'contents': continuation_items}
  2991. for entry in self._post_thread_continuation_entries(continuation_renderer):
  2992. yield entry
  2993. continuation = self._extract_continuation(continuation_renderer)
  2994. continue
  2995. renderer = continuation_item.get('richItemRenderer')
  2996. if renderer:
  2997. for entry in self._rich_grid_entries(continuation_items):
  2998. yield entry
  2999. continuation = self._extract_continuation({'contents': continuation_items})
  3000. continue
  3001. break
  3002. @staticmethod
  3003. def _extract_selected_tab(tabs):
  3004. for tab in tabs:
  3005. renderer = dict_get(tab, ('tabRenderer', 'expandableTabRenderer')) or {}
  3006. if renderer.get('selected') is True:
  3007. return renderer
  3008. else:
  3009. raise ExtractorError('Unable to find selected tab')
  3010. def _extract_uploader(self, metadata, data):
  3011. uploader = {}
  3012. renderers = traverse_obj(data,
  3013. ('sidebar', 'playlistSidebarRenderer', 'items'))
  3014. uploader['channel_id'] = self._extract_channel_id('', metadata=metadata, renderers=renderers)
  3015. uploader['uploader'] = (
  3016. self._extract_author_var('', 'name', renderers=renderers)
  3017. or self._extract_author_var('', 'name', metadata=metadata))
  3018. uploader['uploader_url'] = self._yt_urljoin(
  3019. self._extract_author_var('', 'url', metadata=metadata, renderers=renderers))
  3020. uploader['uploader_id'] = self._extract_uploader_id(uploader['uploader_url'])
  3021. uploader['channel'] = uploader['uploader']
  3022. return uploader
  3023. @staticmethod
  3024. def _extract_alert(data):
  3025. alerts = []
  3026. for alert in try_get(data, lambda x: x['alerts'], list) or []:
  3027. if not isinstance(alert, dict):
  3028. continue
  3029. alert_text = try_get(
  3030. alert, lambda x: x['alertRenderer']['text'], dict)
  3031. if not alert_text:
  3032. continue
  3033. text = try_get(
  3034. alert_text,
  3035. (lambda x: x['simpleText'], lambda x: x['runs'][0]['text']),
  3036. compat_str)
  3037. if text:
  3038. alerts.append(text)
  3039. return '\n'.join(alerts)
  3040. def _extract_from_tabs(self, item_id, webpage, data, tabs):
  3041. selected_tab = self._extract_selected_tab(tabs)
  3042. renderer = try_get(
  3043. data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
  3044. playlist_id = item_id
  3045. title = description = None
  3046. if renderer:
  3047. channel_title = renderer.get('title') or item_id
  3048. tab_title = selected_tab.get('title')
  3049. title = channel_title or item_id
  3050. if tab_title:
  3051. title += ' - %s' % tab_title
  3052. if selected_tab.get('expandedText'):
  3053. title += ' - %s' % selected_tab['expandedText']
  3054. description = renderer.get('description')
  3055. playlist_id = renderer.get('externalId')
  3056. else:
  3057. renderer = try_get(
  3058. data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
  3059. if renderer:
  3060. title = renderer.get('title')
  3061. else:
  3062. renderer = try_get(
  3063. data, lambda x: x['header']['hashtagHeaderRenderer'], dict)
  3064. if renderer:
  3065. title = try_get(renderer, lambda x: x['hashtag']['simpleText'])
  3066. playlist = self.playlist_result(
  3067. self._entries(selected_tab, item_id, webpage),
  3068. playlist_id=playlist_id, playlist_title=title,
  3069. playlist_description=description)
  3070. return merge_dicts(playlist, self._extract_uploader(renderer, data))
  3071. def _extract_from_playlist(self, item_id, url, data, playlist):
  3072. title = playlist.get('title') or try_get(
  3073. data, lambda x: x['titleText']['simpleText'], compat_str)
  3074. playlist_id = playlist.get('playlistId') or item_id
  3075. # Inline playlist rendition continuation does not always work
  3076. # at Youtube side, so delegating regular tab-based playlist URL
  3077. # processing whenever possible.
  3078. playlist_url = urljoin(url, try_get(
  3079. playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  3080. compat_str))
  3081. if playlist_url and playlist_url != url:
  3082. return self.url_result(
  3083. playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  3084. video_title=title)
  3085. return self.playlist_result(
  3086. self._playlist_entries(playlist), playlist_id=playlist_id,
  3087. playlist_title=title)
  3088. def _extract_identity_token(self, ytcfg, webpage):
  3089. if ytcfg:
  3090. token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
  3091. if token:
  3092. return token
  3093. return self._search_regex(
  3094. r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
  3095. 'identity token', default=None)
  3096. def _real_extract(self, url):
  3097. item_id = self._match_id(url)
  3098. url = update_url(url, netloc='www.youtube.com')
  3099. # Handle both video/playlist URLs
  3100. qs = parse_qs(url)
  3101. video_id = qs.get('v', [None])[0]
  3102. playlist_id = qs.get('list', [None])[0]
  3103. if video_id and playlist_id:
  3104. if self._downloader.params.get('noplaylist'):
  3105. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  3106. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  3107. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  3108. webpage = self._download_webpage(url, item_id)
  3109. data = self._extract_yt_initial_data(item_id, webpage)
  3110. tabs = try_get(
  3111. data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
  3112. if tabs:
  3113. return self._extract_from_tabs(item_id, webpage, data, tabs)
  3114. playlist = try_get(
  3115. data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
  3116. if playlist:
  3117. return self._extract_from_playlist(item_id, url, data, playlist)
  3118. # Fallback to video extraction if no playlist alike page is recognized.
  3119. # First check for the current video then try the v attribute of URL query.
  3120. video_id = try_get(
  3121. data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
  3122. compat_str) or video_id
  3123. if video_id:
  3124. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  3125. # Capture and output alerts
  3126. alert = self._extract_alert(data)
  3127. if alert:
  3128. raise ExtractorError(alert, expected=True)
  3129. # Failed to recognize
  3130. raise ExtractorError('Unable to recognize tab page')
  3131. class YoutubePlaylistIE(InfoExtractor):
  3132. IE_DESC = 'YouTube.com playlists'
  3133. _VALID_URL = r'''(?x)(?:
  3134. (?:https?://)?
  3135. (?:\w+\.)?
  3136. (?:
  3137. (?:
  3138. youtube(?:kids)?\.com|
  3139. invidio\.us
  3140. )
  3141. /.*?\?.*?\blist=
  3142. )?
  3143. (?P<id>%(playlist_id)s)
  3144. )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  3145. IE_NAME = 'youtube:playlist'
  3146. _TESTS = [{
  3147. 'note': 'issue #673',
  3148. 'url': 'PLBB231211A4F62143',
  3149. 'info_dict': {
  3150. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  3151. 'id': 'PLBB231211A4F62143',
  3152. 'uploader': 'Wickman',
  3153. 'uploader_id': '@WickmanVT',
  3154. 'channel_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
  3155. },
  3156. 'playlist_mincount': 29,
  3157. }, {
  3158. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  3159. 'info_dict': {
  3160. 'title': 'YDL_safe_search',
  3161. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  3162. },
  3163. 'playlist_count': 2,
  3164. 'skip': 'This playlist is private',
  3165. }, {
  3166. 'note': 'embedded',
  3167. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  3168. # TODO: full playlist requires _reload_with_unavailable_videos()
  3169. # 'playlist_count': 4,
  3170. 'playlist_mincount': 1,
  3171. 'info_dict': {
  3172. 'title': 'JODA15',
  3173. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  3174. 'uploader': 'milan',
  3175. 'uploader_id': '@milan5503',
  3176. 'channel_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  3177. }
  3178. }, {
  3179. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  3180. 'playlist_mincount': 455,
  3181. 'info_dict': {
  3182. 'title': '2018 Chinese New Singles (11/6 updated)',
  3183. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  3184. 'uploader': 'LBK',
  3185. 'uploader_id': '@music_king',
  3186. 'channel_id': 'UC21nz3_MesPLqtDqwdvnoxA',
  3187. }
  3188. }, {
  3189. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  3190. 'only_matching': True,
  3191. }, {
  3192. # music album playlist
  3193. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  3194. 'only_matching': True,
  3195. }]
  3196. @classmethod
  3197. def suitable(cls, url):
  3198. if YoutubeTabIE.suitable(url):
  3199. return False
  3200. if parse_qs(url).get('v', [None])[0]:
  3201. return False
  3202. return super(YoutubePlaylistIE, cls).suitable(url)
  3203. def _real_extract(self, url):
  3204. playlist_id = self._match_id(url)
  3205. qs = parse_qs(url)
  3206. if not qs:
  3207. qs = {'list': playlist_id}
  3208. return self.url_result(
  3209. update_url_query('https://www.youtube.com/playlist', qs),
  3210. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  3211. class YoutubeYtBeIE(InfoExtractor):
  3212. _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}
  3213. _TESTS = [{
  3214. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  3215. 'info_dict': {
  3216. 'id': 'yeWKywCrFtk',
  3217. 'ext': 'mp4',
  3218. 'title': 'Small Scale Baler and Braiding Rugs',
  3219. 'uploader': 'Backus-Page House Museum',
  3220. 'uploader_id': '@backuspagemuseum',
  3221. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/@backuspagemuseum',
  3222. 'upload_date': '20161008',
  3223. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  3224. 'categories': ['Nonprofits & Activism'],
  3225. 'tags': list,
  3226. 'like_count': int,
  3227. },
  3228. 'params': {
  3229. 'noplaylist': True,
  3230. 'skip_download': True,
  3231. },
  3232. }, {
  3233. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  3234. 'only_matching': True,
  3235. }]
  3236. def _real_extract(self, url):
  3237. mobj = re.match(self._VALID_URL, url)
  3238. video_id = mobj.group('id')
  3239. playlist_id = mobj.group('playlist_id')
  3240. return self.url_result(
  3241. update_url_query('https://www.youtube.com/watch', {
  3242. 'v': video_id,
  3243. 'list': playlist_id,
  3244. 'feature': 'youtu.be',
  3245. }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  3246. class YoutubeYtUserIE(InfoExtractor):
  3247. _VALID_URL = r'ytuser:(?P<id>.+)'
  3248. _TESTS = [{
  3249. 'url': 'ytuser:phihag',
  3250. 'only_matching': True,
  3251. }]
  3252. def _real_extract(self, url):
  3253. user_id = self._match_id(url)
  3254. return self.url_result(
  3255. 'https://www.youtube.com/user/%s' % user_id,
  3256. ie=YoutubeTabIE.ie_key(), video_id=user_id)
  3257. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  3258. IE_NAME = 'youtube:favorites'
  3259. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  3260. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  3261. _LOGIN_REQUIRED = True
  3262. _TESTS = [{
  3263. 'url': ':ytfav',
  3264. 'only_matching': True,
  3265. }, {
  3266. 'url': ':ytfavorites',
  3267. 'only_matching': True,
  3268. }]
  3269. def _real_extract(self, url):
  3270. return self.url_result(
  3271. 'https://www.youtube.com/playlist?list=LL',
  3272. ie=YoutubeTabIE.ie_key())
  3273. class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
  3274. IE_DESC = 'YouTube.com searches'
  3275. IE_NAME = 'youtube:search'
  3276. _SEARCH_KEY = 'ytsearch'
  3277. _SEARCH_PARAMS = 'EgIQAQ%3D%3D' # Videos only
  3278. _MAX_RESULTS = float('inf')
  3279. _TESTS = [{
  3280. 'url': 'ytsearch10:youtube-dl test video',
  3281. 'playlist_count': 10,
  3282. 'info_dict': {
  3283. 'id': 'youtube-dl test video',
  3284. 'title': 'youtube-dl test video',
  3285. }
  3286. }]
  3287. def _get_n_results(self, query, n):
  3288. """Get a specified number of results for a query"""
  3289. entries = itertools.islice(self._search_results(query, self._SEARCH_PARAMS), 0, None if n == float('inf') else n)
  3290. return self.playlist_result(entries, query, query)
  3291. class YoutubeSearchDateIE(YoutubeSearchIE):
  3292. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  3293. _SEARCH_KEY = 'ytsearchdate'
  3294. IE_DESC = 'YouTube.com searches, newest videos first'
  3295. _SEARCH_PARAMS = 'CAISAhAB' # Videos only, sorted by date
  3296. _TESTS = [{
  3297. 'url': 'ytsearchdate10:youtube-dl test video',
  3298. 'playlist_count': 10,
  3299. 'info_dict': {
  3300. 'id': 'youtube-dl test video',
  3301. 'title': 'youtube-dl test video',
  3302. }
  3303. }]
  3304. class YoutubeSearchURLIE(YoutubeBaseInfoExtractor):
  3305. IE_DESC = 'YouTube search URLs with sorting and filter support'
  3306. IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
  3307. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
  3308. _TESTS = [{
  3309. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  3310. 'playlist_mincount': 5,
  3311. 'info_dict': {
  3312. 'id': 'youtube-dl test video',
  3313. 'title': 'youtube-dl test video',
  3314. },
  3315. 'params': {'playlistend': 5}
  3316. }, {
  3317. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  3318. 'only_matching': True,
  3319. }]
  3320. def _real_extract(self, url):
  3321. qs = parse_qs(url)
  3322. query = (qs.get('search_query') or qs.get('q'))[-1]
  3323. params = qs.get('sp', ('',))[-1]
  3324. return self.playlist_result(self._search_results(query, params), query, query)
  3325. class YoutubeFeedsInfoExtractor(YoutubeTabIE):
  3326. """
  3327. Base class for feed extractors
  3328. Subclasses must define the _FEED_NAME property.
  3329. """
  3330. _LOGIN_REQUIRED = True
  3331. @property
  3332. def IE_NAME(self):
  3333. return 'youtube:%s' % self._FEED_NAME
  3334. def _real_initialize(self):
  3335. self._login()
  3336. def _real_extract(self, url):
  3337. return self.url_result(
  3338. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  3339. ie=YoutubeTabIE.ie_key())
  3340. class YoutubeWatchLaterIE(InfoExtractor):
  3341. IE_NAME = 'youtube:watchlater'
  3342. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  3343. _VALID_URL = r':ytwatchlater'
  3344. _TESTS = [{
  3345. 'url': ':ytwatchlater',
  3346. 'only_matching': True,
  3347. }]
  3348. def _real_extract(self, url):
  3349. return self.url_result(
  3350. 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
  3351. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  3352. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  3353. _VALID_URL = r':ytrec(?:ommended)?'
  3354. _FEED_NAME = 'recommended'
  3355. _TESTS = [{
  3356. 'url': ':ytrec',
  3357. 'only_matching': True,
  3358. }, {
  3359. 'url': ':ytrecommended',
  3360. 'only_matching': True,
  3361. }]
  3362. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  3363. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  3364. _VALID_URL = r':ytsubs(?:criptions)?'
  3365. _FEED_NAME = 'subscriptions'
  3366. _TESTS = [{
  3367. 'url': ':ytsubs',
  3368. 'only_matching': True,
  3369. }, {
  3370. 'url': ':ytsubscriptions',
  3371. 'only_matching': True,
  3372. }]
  3373. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  3374. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  3375. _VALID_URL = r':ythistory'
  3376. _FEED_NAME = 'history'
  3377. _TESTS = [{
  3378. 'url': ':ythistory',
  3379. 'only_matching': True,
  3380. }]
  3381. class YoutubeTruncatedURLIE(InfoExtractor):
  3382. IE_NAME = 'youtube:truncated_url'
  3383. IE_DESC = False # Do not list
  3384. _VALID_URL = r'''(?x)
  3385. (?:https?://)?
  3386. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  3387. (?:watch\?(?:
  3388. feature=[a-z_]+|
  3389. annotation_id=annotation_[^&]+|
  3390. x-yt-cl=[0-9]+|
  3391. hl=[^&]*|
  3392. t=[0-9]+
  3393. )?
  3394. |
  3395. attribution_link\?a=[^&]+
  3396. )
  3397. $
  3398. '''
  3399. _TESTS = [{
  3400. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  3401. 'only_matching': True,
  3402. }, {
  3403. 'url': 'https://www.youtube.com/watch?',
  3404. 'only_matching': True,
  3405. }, {
  3406. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  3407. 'only_matching': True,
  3408. }, {
  3409. 'url': 'https://www.youtube.com/watch?feature=foo',
  3410. 'only_matching': True,
  3411. }, {
  3412. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  3413. 'only_matching': True,
  3414. }, {
  3415. 'url': 'https://www.youtube.com/watch?t=2372',
  3416. 'only_matching': True,
  3417. }]
  3418. def _real_extract(self, url):
  3419. raise ExtractorError(
  3420. 'Did you forget to quote the URL? Remember that & is a meta '
  3421. 'character in most shells, so you want to put the URL in quotes, '
  3422. 'like youtube-dl '
  3423. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  3424. ' or simply youtube-dl BaW_jenozKc .',
  3425. expected=True)
  3426. class YoutubeTruncatedIDIE(InfoExtractor):
  3427. IE_NAME = 'youtube:truncated_id'
  3428. IE_DESC = False # Do not list
  3429. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  3430. _TESTS = [{
  3431. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  3432. 'only_matching': True,
  3433. }]
  3434. def _real_extract(self, url):
  3435. video_id = self._match_id(url)
  3436. raise ExtractorError(
  3437. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  3438. expected=True)