youtube.py 167 KB

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