youtube.py 140 KB

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