youtube.py 153 KB

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