youtube.py 145 KB

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