youtube.py 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254
  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. pr = self._parse_json(try_get(compat_parse_qs(
  1411. self._download_webpage(
  1412. base_url + 'get_video_info', video_id,
  1413. 'Refetching age-gated info webpage',
  1414. 'unable to download video info webpage', query={
  1415. 'video_id': video_id,
  1416. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1417. 'html5': 1,
  1418. # See https://github.com/ytdl-org/youtube-dl/issues/29333#issuecomment-864049544
  1419. 'c': 'TVHTML5',
  1420. 'cver': '6.20180913',
  1421. }, fatal=False)),
  1422. lambda x: x['player_response'][0],
  1423. compat_str) or '{}', video_id)
  1424. if pr:
  1425. player_response = pr
  1426. trailer_video_id = try_get(
  1427. playability_status,
  1428. lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
  1429. compat_str)
  1430. if trailer_video_id:
  1431. return self.url_result(
  1432. trailer_video_id, self.ie_key(), trailer_video_id)
  1433. def get_text(x):
  1434. if not x:
  1435. return
  1436. text = x.get('simpleText')
  1437. if text and isinstance(text, compat_str):
  1438. return text
  1439. runs = x.get('runs')
  1440. if not isinstance(runs, list):
  1441. return
  1442. return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
  1443. search_meta = (
  1444. lambda x: self._html_search_meta(x, webpage, default=None)) \
  1445. if webpage else lambda x: None
  1446. video_details = player_response.get('videoDetails') or {}
  1447. microformat = try_get(
  1448. player_response,
  1449. lambda x: x['microformat']['playerMicroformatRenderer'],
  1450. dict) or {}
  1451. video_title = video_details.get('title') \
  1452. or get_text(microformat.get('title')) \
  1453. or search_meta(['og:title', 'twitter:title', 'title'])
  1454. video_description = video_details.get('shortDescription')
  1455. if not smuggled_data.get('force_singlefeed', False):
  1456. if not self._downloader.params.get('noplaylist'):
  1457. multifeed_metadata_list = try_get(
  1458. player_response,
  1459. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1460. compat_str)
  1461. if multifeed_metadata_list:
  1462. entries = []
  1463. feed_ids = []
  1464. for feed in multifeed_metadata_list.split(','):
  1465. # Unquote should take place before split on comma (,) since textual
  1466. # fields may contain comma as well (see
  1467. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1468. feed_data = compat_parse_qs(
  1469. compat_urllib_parse_unquote_plus(feed))
  1470. def feed_entry(name):
  1471. return try_get(
  1472. feed_data, lambda x: x[name][0], compat_str)
  1473. feed_id = feed_entry('id')
  1474. if not feed_id:
  1475. continue
  1476. feed_title = feed_entry('title')
  1477. title = video_title
  1478. if feed_title:
  1479. title += ' (%s)' % feed_title
  1480. entries.append({
  1481. '_type': 'url_transparent',
  1482. 'ie_key': 'Youtube',
  1483. 'url': smuggle_url(
  1484. base_url + 'watch?v=' + feed_data['id'][0],
  1485. {'force_singlefeed': True}),
  1486. 'title': title,
  1487. })
  1488. feed_ids.append(feed_id)
  1489. self.to_screen(
  1490. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1491. % (', '.join(feed_ids), video_id))
  1492. return self.playlist_result(
  1493. entries, video_id, video_title, video_description)
  1494. else:
  1495. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1496. formats = []
  1497. itags = []
  1498. itag_qualities = {}
  1499. player_url = None
  1500. q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
  1501. streaming_data = player_response.get('streamingData') or {}
  1502. streaming_formats = streaming_data.get('formats') or []
  1503. streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
  1504. for fmt in streaming_formats:
  1505. if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
  1506. continue
  1507. itag = str_or_none(fmt.get('itag'))
  1508. quality = fmt.get('quality')
  1509. if itag and quality:
  1510. itag_qualities[itag] = quality
  1511. # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
  1512. # (adding `&sq=0` to the URL) and parsing emsg box to determine the
  1513. # number of fragment that would subsequently requested with (`&sq=N`)
  1514. if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
  1515. continue
  1516. fmt_url = fmt.get('url')
  1517. if not fmt_url:
  1518. sc = compat_parse_qs(fmt.get('signatureCipher'))
  1519. fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
  1520. encrypted_sig = try_get(sc, lambda x: x['s'][0])
  1521. if not (sc and fmt_url and encrypted_sig):
  1522. continue
  1523. if not player_url:
  1524. if not webpage:
  1525. continue
  1526. player_url = self._search_regex(
  1527. r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
  1528. webpage, 'player URL', fatal=False)
  1529. if not player_url:
  1530. continue
  1531. signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
  1532. sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
  1533. fmt_url += '&' + sp + '=' + signature
  1534. if itag:
  1535. itags.append(itag)
  1536. tbr = float_or_none(
  1537. fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
  1538. dct = {
  1539. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1540. 'filesize': int_or_none(fmt.get('contentLength')),
  1541. 'format_id': itag,
  1542. 'format_note': fmt.get('qualityLabel') or quality,
  1543. 'fps': int_or_none(fmt.get('fps')),
  1544. 'height': int_or_none(fmt.get('height')),
  1545. 'quality': q(quality),
  1546. 'tbr': tbr,
  1547. 'url': fmt_url,
  1548. 'width': fmt.get('width'),
  1549. }
  1550. mimetype = fmt.get('mimeType')
  1551. if mimetype:
  1552. mobj = re.match(
  1553. r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
  1554. if mobj:
  1555. dct['ext'] = mimetype2ext(mobj.group(1))
  1556. dct.update(parse_codecs(mobj.group(2)))
  1557. no_audio = dct.get('acodec') == 'none'
  1558. no_video = dct.get('vcodec') == 'none'
  1559. if no_audio:
  1560. dct['vbr'] = tbr
  1561. if no_video:
  1562. dct['abr'] = tbr
  1563. if no_audio or no_video:
  1564. dct['downloader_options'] = {
  1565. # Youtube throttles chunks >~10M
  1566. 'http_chunk_size': 10485760,
  1567. }
  1568. if dct.get('ext'):
  1569. dct['container'] = dct['ext'] + '_dash'
  1570. formats.append(dct)
  1571. hls_manifest_url = streaming_data.get('hlsManifestUrl')
  1572. if hls_manifest_url:
  1573. for f in self._extract_m3u8_formats(
  1574. hls_manifest_url, video_id, 'mp4', fatal=False):
  1575. itag = self._search_regex(
  1576. r'/itag/(\d+)', f['url'], 'itag', default=None)
  1577. if itag:
  1578. f['format_id'] = itag
  1579. formats.append(f)
  1580. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1581. dash_manifest_url = streaming_data.get('dashManifestUrl')
  1582. if dash_manifest_url:
  1583. for f in self._extract_mpd_formats(
  1584. dash_manifest_url, video_id, fatal=False):
  1585. itag = f['format_id']
  1586. if itag in itags:
  1587. continue
  1588. if itag in itag_qualities:
  1589. f['quality'] = q(itag_qualities[itag])
  1590. filesize = int_or_none(self._search_regex(
  1591. r'/clen/(\d+)', f.get('fragment_base_url')
  1592. or f['url'], 'file size', default=None))
  1593. if filesize:
  1594. f['filesize'] = filesize
  1595. formats.append(f)
  1596. if not formats:
  1597. if streaming_data.get('licenseInfos'):
  1598. raise ExtractorError(
  1599. 'This video is DRM protected.', expected=True)
  1600. pemr = try_get(
  1601. playability_status,
  1602. lambda x: x['errorScreen']['playerErrorMessageRenderer'],
  1603. dict) or {}
  1604. reason = get_text(pemr.get('reason')) or playability_status.get('reason')
  1605. subreason = pemr.get('subreason')
  1606. if subreason:
  1607. subreason = clean_html(get_text(subreason))
  1608. if subreason == 'The uploader has not made this video available in your country.':
  1609. countries = microformat.get('availableCountries')
  1610. if not countries:
  1611. regions_allowed = search_meta('regionsAllowed')
  1612. countries = regions_allowed.split(',') if regions_allowed else None
  1613. self.raise_geo_restricted(
  1614. subreason, countries)
  1615. reason += '\n' + subreason
  1616. if reason:
  1617. raise ExtractorError(reason, expected=True)
  1618. self._sort_formats(formats)
  1619. keywords = video_details.get('keywords') or []
  1620. if not keywords and webpage:
  1621. keywords = [
  1622. unescapeHTML(m.group('content'))
  1623. for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
  1624. for keyword in keywords:
  1625. if keyword.startswith('yt:stretch='):
  1626. mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
  1627. if mobj:
  1628. # NB: float is intentional for forcing float division
  1629. w, h = (float(v) for v in mobj.groups())
  1630. if w > 0 and h > 0:
  1631. ratio = w / h
  1632. for f in formats:
  1633. if f.get('vcodec') != 'none':
  1634. f['stretched_ratio'] = ratio
  1635. break
  1636. thumbnails = []
  1637. for container in (video_details, microformat):
  1638. for thumbnail in (try_get(
  1639. container,
  1640. lambda x: x['thumbnail']['thumbnails'], list) or []):
  1641. thumbnail_url = thumbnail.get('url')
  1642. if not thumbnail_url:
  1643. continue
  1644. thumbnails.append({
  1645. 'height': int_or_none(thumbnail.get('height')),
  1646. 'url': thumbnail_url,
  1647. 'width': int_or_none(thumbnail.get('width')),
  1648. })
  1649. if thumbnails:
  1650. break
  1651. else:
  1652. thumbnail = search_meta(['og:image', 'twitter:image'])
  1653. if thumbnail:
  1654. thumbnails = [{'url': thumbnail}]
  1655. category = microformat.get('category') or search_meta('genre')
  1656. channel_id = video_details.get('channelId') \
  1657. or microformat.get('externalChannelId') \
  1658. or search_meta('channelId')
  1659. duration = int_or_none(
  1660. video_details.get('lengthSeconds')
  1661. or microformat.get('lengthSeconds')) \
  1662. or parse_duration(search_meta('duration'))
  1663. is_live = video_details.get('isLive')
  1664. owner_profile_url = microformat.get('ownerProfileUrl')
  1665. info = {
  1666. 'id': video_id,
  1667. 'title': self._live_title(video_title) if is_live else video_title,
  1668. 'formats': formats,
  1669. 'thumbnails': thumbnails,
  1670. 'description': video_description,
  1671. 'upload_date': unified_strdate(
  1672. microformat.get('uploadDate')
  1673. or search_meta('uploadDate')),
  1674. 'uploader': video_details['author'],
  1675. 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
  1676. 'uploader_url': owner_profile_url,
  1677. 'channel_id': channel_id,
  1678. 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
  1679. 'duration': duration,
  1680. 'view_count': int_or_none(
  1681. video_details.get('viewCount')
  1682. or microformat.get('viewCount')
  1683. or search_meta('interactionCount')),
  1684. 'average_rating': float_or_none(video_details.get('averageRating')),
  1685. 'age_limit': 18 if (
  1686. microformat.get('isFamilySafe') is False
  1687. or search_meta('isFamilyFriendly') == 'false'
  1688. or search_meta('og:restrictions:age') == '18+') else 0,
  1689. 'webpage_url': webpage_url,
  1690. 'categories': [category] if category else None,
  1691. 'tags': keywords,
  1692. 'is_live': is_live,
  1693. }
  1694. pctr = try_get(
  1695. player_response,
  1696. lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
  1697. if pctr:
  1698. def process_language(container, base_url, lang_code, query):
  1699. lang_subs = []
  1700. for fmt in self._SUBTITLE_FORMATS:
  1701. query.update({
  1702. 'fmt': fmt,
  1703. })
  1704. lang_subs.append({
  1705. 'ext': fmt,
  1706. 'url': update_url_query(base_url, query),
  1707. })
  1708. container[lang_code] = lang_subs
  1709. subtitles = {}
  1710. for caption_track in (pctr.get('captionTracks') or []):
  1711. base_url = caption_track.get('baseUrl')
  1712. if not base_url:
  1713. continue
  1714. if caption_track.get('kind') != 'asr':
  1715. lang_code = caption_track.get('languageCode')
  1716. if not lang_code:
  1717. continue
  1718. process_language(
  1719. subtitles, base_url, lang_code, {})
  1720. continue
  1721. automatic_captions = {}
  1722. for translation_language in (pctr.get('translationLanguages') or []):
  1723. translation_language_code = translation_language.get('languageCode')
  1724. if not translation_language_code:
  1725. continue
  1726. process_language(
  1727. automatic_captions, base_url, translation_language_code,
  1728. {'tlang': translation_language_code})
  1729. info['automatic_captions'] = automatic_captions
  1730. info['subtitles'] = subtitles
  1731. parsed_url = compat_urllib_parse_urlparse(url)
  1732. for component in [parsed_url.fragment, parsed_url.query]:
  1733. query = compat_parse_qs(component)
  1734. for k, v in query.items():
  1735. for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
  1736. d_k += '_time'
  1737. if d_k not in info and k in s_ks:
  1738. info[d_k] = parse_duration(query[k][0])
  1739. if video_description:
  1740. 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)
  1741. if mobj:
  1742. release_year = mobj.group('release_year')
  1743. release_date = mobj.group('release_date')
  1744. if release_date:
  1745. release_date = release_date.replace('-', '')
  1746. if not release_year:
  1747. release_year = release_date[:4]
  1748. info.update({
  1749. 'album': mobj.group('album'.strip()),
  1750. 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
  1751. 'track': mobj.group('track').strip(),
  1752. 'release_date': release_date,
  1753. 'release_year': int_or_none(release_year),
  1754. })
  1755. initial_data = None
  1756. if webpage:
  1757. initial_data = self._extract_yt_initial_variable(
  1758. webpage, self._YT_INITIAL_DATA_RE, video_id,
  1759. 'yt initial data')
  1760. if not initial_data:
  1761. initial_data = self._call_api(
  1762. 'next', {'videoId': video_id}, video_id, fatal=False)
  1763. if initial_data:
  1764. chapters = self._extract_chapters_from_json(
  1765. initial_data, video_id, duration)
  1766. if not chapters:
  1767. for engagment_pannel in (initial_data.get('engagementPanels') or []):
  1768. contents = try_get(
  1769. engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
  1770. list)
  1771. if not contents:
  1772. continue
  1773. def chapter_time(mmlir):
  1774. return parse_duration(
  1775. get_text(mmlir.get('timeDescription')))
  1776. chapters = []
  1777. for next_num, content in enumerate(contents, start=1):
  1778. mmlir = content.get('macroMarkersListItemRenderer') or {}
  1779. start_time = chapter_time(mmlir)
  1780. end_time = chapter_time(try_get(
  1781. contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
  1782. if next_num < len(contents) else duration
  1783. if start_time is None or end_time is None:
  1784. continue
  1785. chapters.append({
  1786. 'start_time': start_time,
  1787. 'end_time': end_time,
  1788. 'title': get_text(mmlir.get('title')),
  1789. })
  1790. if chapters:
  1791. break
  1792. if chapters:
  1793. info['chapters'] = chapters
  1794. contents = try_get(
  1795. initial_data,
  1796. lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
  1797. list) or []
  1798. for content in contents:
  1799. vpir = content.get('videoPrimaryInfoRenderer')
  1800. if vpir:
  1801. stl = vpir.get('superTitleLink')
  1802. if stl:
  1803. stl = get_text(stl)
  1804. if try_get(
  1805. vpir,
  1806. lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
  1807. info['location'] = stl
  1808. else:
  1809. mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
  1810. if mobj:
  1811. info.update({
  1812. 'series': mobj.group(1),
  1813. 'season_number': int(mobj.group(2)),
  1814. 'episode_number': int(mobj.group(3)),
  1815. })
  1816. for tlb in (try_get(
  1817. vpir,
  1818. lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
  1819. list) or []):
  1820. tbr = tlb.get('toggleButtonRenderer') or {}
  1821. for getter, regex in [(
  1822. lambda x: x['defaultText']['accessibility']['accessibilityData'],
  1823. r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
  1824. lambda x: x['accessibility'],
  1825. lambda x: x['accessibilityData']['accessibilityData'],
  1826. ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
  1827. label = (try_get(tbr, getter, dict) or {}).get('label')
  1828. if label:
  1829. mobj = re.match(regex, label)
  1830. if mobj:
  1831. info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
  1832. break
  1833. sbr_tooltip = try_get(
  1834. vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
  1835. if sbr_tooltip:
  1836. like_count, dislike_count = sbr_tooltip.split(' / ')
  1837. info.update({
  1838. 'like_count': str_to_int(like_count),
  1839. 'dislike_count': str_to_int(dislike_count),
  1840. })
  1841. vsir = content.get('videoSecondaryInfoRenderer')
  1842. if vsir:
  1843. info['channel'] = get_text(try_get(
  1844. vsir,
  1845. lambda x: x['owner']['videoOwnerRenderer']['title'],
  1846. dict))
  1847. rows = try_get(
  1848. vsir,
  1849. lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
  1850. list) or []
  1851. multiple_songs = False
  1852. for row in rows:
  1853. if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
  1854. multiple_songs = True
  1855. break
  1856. for row in rows:
  1857. mrr = row.get('metadataRowRenderer') or {}
  1858. mrr_title = mrr.get('title')
  1859. if not mrr_title:
  1860. continue
  1861. mrr_title = get_text(mrr['title'])
  1862. mrr_contents_text = get_text(mrr['contents'][0])
  1863. if mrr_title == 'License':
  1864. info['license'] = mrr_contents_text
  1865. elif not multiple_songs:
  1866. if mrr_title == 'Album':
  1867. info['album'] = mrr_contents_text
  1868. elif mrr_title == 'Artist':
  1869. info['artist'] = mrr_contents_text
  1870. elif mrr_title == 'Song':
  1871. info['track'] = mrr_contents_text
  1872. for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
  1873. v = info.get(s_k)
  1874. if v:
  1875. info[d_k] = v
  1876. self.mark_watched(video_id, player_response)
  1877. return info
  1878. class YoutubeTabIE(YoutubeBaseInfoExtractor):
  1879. IE_DESC = 'YouTube.com tab'
  1880. _VALID_URL = r'''(?x)
  1881. https?://
  1882. (?:\w+\.)?
  1883. (?:
  1884. youtube(?:kids)?\.com|
  1885. invidio\.us
  1886. )/
  1887. (?:
  1888. (?:channel|c|user|feed|hashtag)/|
  1889. (?:playlist|watch)\?.*?\blist=|
  1890. (?!(?:watch|embed|v|e)\b)
  1891. )
  1892. (?P<id>[^/?\#&]+)
  1893. '''
  1894. IE_NAME = 'youtube:tab'
  1895. _TESTS = [{
  1896. # playlists, multipage
  1897. 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
  1898. 'playlist_mincount': 94,
  1899. 'info_dict': {
  1900. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  1901. 'title': 'Игорь Клейнер - Playlists',
  1902. 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
  1903. },
  1904. }, {
  1905. # playlists, multipage, different order
  1906. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  1907. 'playlist_mincount': 94,
  1908. 'info_dict': {
  1909. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  1910. 'title': 'Игорь Клейнер - Playlists',
  1911. 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
  1912. },
  1913. }, {
  1914. # playlists, series
  1915. 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
  1916. 'playlist_mincount': 5,
  1917. 'info_dict': {
  1918. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  1919. 'title': '3Blue1Brown - Playlists',
  1920. 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
  1921. },
  1922. }, {
  1923. # playlists, singlepage
  1924. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  1925. 'playlist_mincount': 4,
  1926. 'info_dict': {
  1927. 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
  1928. 'title': 'ThirstForScience - Playlists',
  1929. 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
  1930. }
  1931. }, {
  1932. 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
  1933. 'only_matching': True,
  1934. }, {
  1935. # basic, single video playlist
  1936. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  1937. 'info_dict': {
  1938. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  1939. 'uploader': 'Sergey M.',
  1940. 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  1941. 'title': 'youtube-dl public playlist',
  1942. },
  1943. 'playlist_count': 1,
  1944. }, {
  1945. # empty playlist
  1946. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  1947. 'info_dict': {
  1948. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  1949. 'uploader': 'Sergey M.',
  1950. 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  1951. 'title': 'youtube-dl empty playlist',
  1952. },
  1953. 'playlist_count': 0,
  1954. }, {
  1955. # Home tab
  1956. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
  1957. 'info_dict': {
  1958. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  1959. 'title': 'lex will - Home',
  1960. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  1961. },
  1962. 'playlist_mincount': 2,
  1963. }, {
  1964. # Videos tab
  1965. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
  1966. 'info_dict': {
  1967. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  1968. 'title': 'lex will - Videos',
  1969. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  1970. },
  1971. 'playlist_mincount': 975,
  1972. }, {
  1973. # Videos tab, sorted by popular
  1974. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
  1975. 'info_dict': {
  1976. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  1977. 'title': 'lex will - Videos',
  1978. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  1979. },
  1980. 'playlist_mincount': 199,
  1981. }, {
  1982. # Playlists tab
  1983. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
  1984. 'info_dict': {
  1985. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  1986. 'title': 'lex will - Playlists',
  1987. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  1988. },
  1989. 'playlist_mincount': 17,
  1990. }, {
  1991. # Community tab
  1992. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
  1993. 'info_dict': {
  1994. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  1995. 'title': 'lex will - Community',
  1996. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  1997. },
  1998. 'playlist_mincount': 18,
  1999. }, {
  2000. # Channels tab
  2001. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
  2002. 'info_dict': {
  2003. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2004. 'title': 'lex will - Channels',
  2005. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2006. },
  2007. 'playlist_mincount': 138,
  2008. }, {
  2009. 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2010. 'only_matching': True,
  2011. }, {
  2012. 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2013. 'only_matching': True,
  2014. }, {
  2015. 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2016. 'only_matching': True,
  2017. }, {
  2018. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2019. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2020. 'info_dict': {
  2021. 'title': '29C3: Not my department',
  2022. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2023. 'uploader': 'Christiaan008',
  2024. 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
  2025. },
  2026. 'playlist_count': 96,
  2027. }, {
  2028. 'note': 'Large playlist',
  2029. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2030. 'info_dict': {
  2031. 'title': 'Uploads from Cauchemar',
  2032. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2033. 'uploader': 'Cauchemar',
  2034. 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
  2035. },
  2036. 'playlist_mincount': 1123,
  2037. }, {
  2038. # even larger playlist, 8832 videos
  2039. 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
  2040. 'only_matching': True,
  2041. }, {
  2042. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2043. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2044. 'info_dict': {
  2045. 'title': 'Uploads from Interstellar Movie',
  2046. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2047. 'uploader': 'Interstellar Movie',
  2048. 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
  2049. },
  2050. 'playlist_mincount': 21,
  2051. }, {
  2052. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2053. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2054. 'info_dict': {
  2055. 'title': 'Data Analysis with Dr Mike Pound',
  2056. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2057. 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
  2058. 'uploader': 'Computerphile',
  2059. },
  2060. 'playlist_mincount': 11,
  2061. }, {
  2062. 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2063. 'only_matching': True,
  2064. }, {
  2065. # Playlist URL that does not actually serve a playlist
  2066. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2067. 'info_dict': {
  2068. 'id': 'FqZTN594JQw',
  2069. 'ext': 'webm',
  2070. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2071. 'uploader': 'STREEM',
  2072. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2073. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2074. 'upload_date': '20150526',
  2075. 'license': 'Standard YouTube License',
  2076. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2077. 'categories': ['People & Blogs'],
  2078. 'tags': list,
  2079. 'view_count': int,
  2080. 'like_count': int,
  2081. 'dislike_count': int,
  2082. },
  2083. 'params': {
  2084. 'skip_download': True,
  2085. },
  2086. 'skip': 'This video is not available.',
  2087. 'add_ie': [YoutubeIE.ie_key()],
  2088. }, {
  2089. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  2090. 'only_matching': True,
  2091. }, {
  2092. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  2093. 'only_matching': True,
  2094. }, {
  2095. 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
  2096. 'info_dict': {
  2097. 'id': '9Auq9mYxFEE',
  2098. 'ext': 'mp4',
  2099. 'title': 'Watch Sky News live',
  2100. 'uploader': 'Sky News',
  2101. 'uploader_id': 'skynews',
  2102. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
  2103. 'upload_date': '20191102',
  2104. 'description': 'md5:78de4e1c2359d0ea3ed829678e38b662',
  2105. 'categories': ['News & Politics'],
  2106. 'tags': list,
  2107. 'like_count': int,
  2108. 'dislike_count': int,
  2109. },
  2110. 'params': {
  2111. 'skip_download': True,
  2112. },
  2113. }, {
  2114. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2115. 'info_dict': {
  2116. 'id': 'a48o2S1cPoo',
  2117. 'ext': 'mp4',
  2118. 'title': 'The Young Turks - Live Main Show',
  2119. 'uploader': 'The Young Turks',
  2120. 'uploader_id': 'TheYoungTurks',
  2121. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2122. 'upload_date': '20150715',
  2123. 'license': 'Standard YouTube License',
  2124. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2125. 'categories': ['News & Politics'],
  2126. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2127. 'like_count': int,
  2128. 'dislike_count': int,
  2129. },
  2130. 'params': {
  2131. 'skip_download': True,
  2132. },
  2133. 'only_matching': True,
  2134. }, {
  2135. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2136. 'only_matching': True,
  2137. }, {
  2138. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2139. 'only_matching': True,
  2140. }, {
  2141. 'url': 'https://www.youtube.com/feed/trending',
  2142. 'only_matching': True,
  2143. }, {
  2144. # needs auth
  2145. 'url': 'https://www.youtube.com/feed/library',
  2146. 'only_matching': True,
  2147. }, {
  2148. # needs auth
  2149. 'url': 'https://www.youtube.com/feed/history',
  2150. 'only_matching': True,
  2151. }, {
  2152. # needs auth
  2153. 'url': 'https://www.youtube.com/feed/subscriptions',
  2154. 'only_matching': True,
  2155. }, {
  2156. # needs auth
  2157. 'url': 'https://www.youtube.com/feed/watch_later',
  2158. 'only_matching': True,
  2159. }, {
  2160. # no longer available?
  2161. 'url': 'https://www.youtube.com/feed/recommended',
  2162. 'only_matching': True,
  2163. }, {
  2164. # inline playlist with not always working continuations
  2165. 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
  2166. 'only_matching': True,
  2167. }, {
  2168. 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
  2169. 'only_matching': True,
  2170. }, {
  2171. 'url': 'https://www.youtube.com/course',
  2172. 'only_matching': True,
  2173. }, {
  2174. 'url': 'https://www.youtube.com/zsecurity',
  2175. 'only_matching': True,
  2176. }, {
  2177. 'url': 'http://www.youtube.com/NASAgovVideo/videos',
  2178. 'only_matching': True,
  2179. }, {
  2180. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2181. 'only_matching': True,
  2182. }, {
  2183. 'url': 'https://www.youtube.com/hashtag/cctv9',
  2184. 'info_dict': {
  2185. 'id': 'cctv9',
  2186. 'title': '#cctv9',
  2187. },
  2188. 'playlist_mincount': 350,
  2189. }, {
  2190. 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
  2191. 'only_matching': True,
  2192. }]
  2193. @classmethod
  2194. def suitable(cls, url):
  2195. return False if YoutubeIE.suitable(url) else super(
  2196. YoutubeTabIE, cls).suitable(url)
  2197. def _extract_channel_id(self, webpage):
  2198. channel_id = self._html_search_meta(
  2199. 'channelId', webpage, 'channel id', default=None)
  2200. if channel_id:
  2201. return channel_id
  2202. channel_url = self._html_search_meta(
  2203. ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
  2204. 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
  2205. 'twitter:app:url:googleplay'), webpage, 'channel url')
  2206. return self._search_regex(
  2207. r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
  2208. channel_url, 'channel id')
  2209. @staticmethod
  2210. def _extract_grid_item_renderer(item):
  2211. assert isinstance(item, dict)
  2212. for key, renderer in item.items():
  2213. if not key.startswith('grid') or not key.endswith('Renderer'):
  2214. continue
  2215. if not isinstance(renderer, dict):
  2216. continue
  2217. return renderer
  2218. def _grid_entries(self, grid_renderer):
  2219. for item in grid_renderer['items']:
  2220. if not isinstance(item, dict):
  2221. continue
  2222. renderer = self._extract_grid_item_renderer(item)
  2223. if not isinstance(renderer, dict):
  2224. continue
  2225. title = try_get(
  2226. renderer, (lambda x: x['title']['runs'][0]['text'],
  2227. lambda x: x['title']['simpleText']), compat_str)
  2228. # playlist
  2229. playlist_id = renderer.get('playlistId')
  2230. if playlist_id:
  2231. yield self.url_result(
  2232. 'https://www.youtube.com/playlist?list=%s' % playlist_id,
  2233. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  2234. video_title=title)
  2235. continue
  2236. # video
  2237. video_id = renderer.get('videoId')
  2238. if video_id:
  2239. yield self._extract_video(renderer)
  2240. continue
  2241. # channel
  2242. channel_id = renderer.get('channelId')
  2243. if channel_id:
  2244. title = try_get(
  2245. renderer, lambda x: x['title']['simpleText'], compat_str)
  2246. yield self.url_result(
  2247. 'https://www.youtube.com/channel/%s' % channel_id,
  2248. ie=YoutubeTabIE.ie_key(), video_title=title)
  2249. continue
  2250. # generic endpoint URL support
  2251. ep_url = urljoin('https://www.youtube.com/', try_get(
  2252. renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
  2253. compat_str))
  2254. if ep_url:
  2255. for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
  2256. if ie.suitable(ep_url):
  2257. yield self.url_result(
  2258. ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
  2259. break
  2260. def _shelf_entries_from_content(self, shelf_renderer):
  2261. content = shelf_renderer.get('content')
  2262. if not isinstance(content, dict):
  2263. return
  2264. renderer = content.get('gridRenderer')
  2265. if renderer:
  2266. # TODO: add support for nested playlists so each shelf is processed
  2267. # as separate playlist
  2268. # TODO: this includes only first N items
  2269. for entry in self._grid_entries(renderer):
  2270. yield entry
  2271. renderer = content.get('horizontalListRenderer')
  2272. if renderer:
  2273. # TODO
  2274. pass
  2275. def _shelf_entries(self, shelf_renderer, skip_channels=False):
  2276. ep = try_get(
  2277. shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  2278. compat_str)
  2279. shelf_url = urljoin('https://www.youtube.com', ep)
  2280. if shelf_url:
  2281. # Skipping links to another channels, note that checking for
  2282. # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
  2283. # will not work
  2284. if skip_channels and '/channels?' in shelf_url:
  2285. return
  2286. title = try_get(
  2287. shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
  2288. yield self.url_result(shelf_url, video_title=title)
  2289. # Shelf may not contain shelf URL, fallback to extraction from content
  2290. for entry in self._shelf_entries_from_content(shelf_renderer):
  2291. yield entry
  2292. def _playlist_entries(self, video_list_renderer):
  2293. for content in video_list_renderer['contents']:
  2294. if not isinstance(content, dict):
  2295. continue
  2296. renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
  2297. if not isinstance(renderer, dict):
  2298. continue
  2299. video_id = renderer.get('videoId')
  2300. if not video_id:
  2301. continue
  2302. yield self._extract_video(renderer)
  2303. def _video_entry(self, video_renderer):
  2304. video_id = video_renderer.get('videoId')
  2305. if video_id:
  2306. return self._extract_video(video_renderer)
  2307. def _post_thread_entries(self, post_thread_renderer):
  2308. post_renderer = try_get(
  2309. post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
  2310. if not post_renderer:
  2311. return
  2312. # video attachment
  2313. video_renderer = try_get(
  2314. post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
  2315. video_id = None
  2316. if video_renderer:
  2317. entry = self._video_entry(video_renderer)
  2318. if entry:
  2319. yield entry
  2320. # inline video links
  2321. runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
  2322. for run in runs:
  2323. if not isinstance(run, dict):
  2324. continue
  2325. ep_url = try_get(
  2326. run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
  2327. if not ep_url:
  2328. continue
  2329. if not YoutubeIE.suitable(ep_url):
  2330. continue
  2331. ep_video_id = YoutubeIE._match_id(ep_url)
  2332. if video_id == ep_video_id:
  2333. continue
  2334. yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
  2335. def _post_thread_continuation_entries(self, post_thread_continuation):
  2336. contents = post_thread_continuation.get('contents')
  2337. if not isinstance(contents, list):
  2338. return
  2339. for content in contents:
  2340. renderer = content.get('backstagePostThreadRenderer')
  2341. if not isinstance(renderer, dict):
  2342. continue
  2343. for entry in self._post_thread_entries(renderer):
  2344. yield entry
  2345. def _rich_grid_entries(self, contents):
  2346. for content in contents:
  2347. video_renderer = try_get(content, lambda x: x['richItemRenderer']['content']['videoRenderer'], dict)
  2348. if video_renderer:
  2349. entry = self._video_entry(video_renderer)
  2350. if entry:
  2351. yield entry
  2352. @staticmethod
  2353. def _build_continuation_query(continuation, ctp=None):
  2354. query = {
  2355. 'ctoken': continuation,
  2356. 'continuation': continuation,
  2357. }
  2358. if ctp:
  2359. query['itct'] = ctp
  2360. return query
  2361. @staticmethod
  2362. def _extract_next_continuation_data(renderer):
  2363. next_continuation = try_get(
  2364. renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
  2365. if not next_continuation:
  2366. return
  2367. continuation = next_continuation.get('continuation')
  2368. if not continuation:
  2369. return
  2370. ctp = next_continuation.get('clickTrackingParams')
  2371. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  2372. @classmethod
  2373. def _extract_continuation(cls, renderer):
  2374. next_continuation = cls._extract_next_continuation_data(renderer)
  2375. if next_continuation:
  2376. return next_continuation
  2377. contents = []
  2378. for key in ('contents', 'items'):
  2379. contents.extend(try_get(renderer, lambda x: x[key], list) or [])
  2380. for content in contents:
  2381. if not isinstance(content, dict):
  2382. continue
  2383. continuation_ep = try_get(
  2384. content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
  2385. dict)
  2386. if not continuation_ep:
  2387. continue
  2388. continuation = try_get(
  2389. continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
  2390. if not continuation:
  2391. continue
  2392. ctp = continuation_ep.get('clickTrackingParams')
  2393. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  2394. def _entries(self, tab, item_id, webpage):
  2395. tab_content = try_get(tab, lambda x: x['content'], dict)
  2396. if not tab_content:
  2397. return
  2398. slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
  2399. if slr_renderer:
  2400. is_channels_tab = tab.get('title') == 'Channels'
  2401. continuation = None
  2402. slr_contents = try_get(slr_renderer, lambda x: x['contents'], list) or []
  2403. for slr_content in slr_contents:
  2404. if not isinstance(slr_content, dict):
  2405. continue
  2406. is_renderer = try_get(slr_content, lambda x: x['itemSectionRenderer'], dict)
  2407. if not is_renderer:
  2408. continue
  2409. isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
  2410. for isr_content in isr_contents:
  2411. if not isinstance(isr_content, dict):
  2412. continue
  2413. renderer = isr_content.get('playlistVideoListRenderer')
  2414. if renderer:
  2415. for entry in self._playlist_entries(renderer):
  2416. yield entry
  2417. continuation = self._extract_continuation(renderer)
  2418. continue
  2419. renderer = isr_content.get('gridRenderer')
  2420. if renderer:
  2421. for entry in self._grid_entries(renderer):
  2422. yield entry
  2423. continuation = self._extract_continuation(renderer)
  2424. continue
  2425. renderer = isr_content.get('shelfRenderer')
  2426. if renderer:
  2427. for entry in self._shelf_entries(renderer, not is_channels_tab):
  2428. yield entry
  2429. continue
  2430. renderer = isr_content.get('backstagePostThreadRenderer')
  2431. if renderer:
  2432. for entry in self._post_thread_entries(renderer):
  2433. yield entry
  2434. continuation = self._extract_continuation(renderer)
  2435. continue
  2436. renderer = isr_content.get('videoRenderer')
  2437. if renderer:
  2438. entry = self._video_entry(renderer)
  2439. if entry:
  2440. yield entry
  2441. if not continuation:
  2442. continuation = self._extract_continuation(is_renderer)
  2443. if not continuation:
  2444. continuation = self._extract_continuation(slr_renderer)
  2445. else:
  2446. rich_grid_renderer = tab_content.get('richGridRenderer')
  2447. if not rich_grid_renderer:
  2448. return
  2449. for entry in self._rich_grid_entries(rich_grid_renderer.get('contents') or []):
  2450. yield entry
  2451. continuation = self._extract_continuation(rich_grid_renderer)
  2452. ytcfg = self._extract_ytcfg(item_id, webpage)
  2453. client_version = try_get(
  2454. ytcfg, lambda x: x['INNERTUBE_CLIENT_VERSION'], compat_str) or '2.20210407.08.00'
  2455. headers = {
  2456. 'x-youtube-client-name': '1',
  2457. 'x-youtube-client-version': client_version,
  2458. 'content-type': 'application/json',
  2459. }
  2460. context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'], dict) or {
  2461. 'client': {
  2462. 'clientName': 'WEB',
  2463. 'clientVersion': client_version,
  2464. }
  2465. }
  2466. visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
  2467. identity_token = self._extract_identity_token(ytcfg, webpage)
  2468. if identity_token:
  2469. headers['x-youtube-identity-token'] = identity_token
  2470. data = {
  2471. 'context': context,
  2472. }
  2473. for page_num in itertools.count(1):
  2474. if not continuation:
  2475. break
  2476. if visitor_data:
  2477. headers['x-goog-visitor-id'] = visitor_data
  2478. data['continuation'] = continuation['continuation']
  2479. data['clickTracking'] = {
  2480. 'clickTrackingParams': continuation['itct']
  2481. }
  2482. count = 0
  2483. retries = 3
  2484. while count <= retries:
  2485. try:
  2486. # Downloading page may result in intermittent 5xx HTTP error
  2487. # that is usually worked around with a retry
  2488. response = self._download_json(
  2489. 'https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  2490. None, 'Downloading page %d%s' % (page_num, ' (retry #%d)' % count if count else ''),
  2491. headers=headers, data=json.dumps(data).encode('utf8'))
  2492. break
  2493. except ExtractorError as e:
  2494. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  2495. count += 1
  2496. if count <= retries:
  2497. continue
  2498. raise
  2499. if not response:
  2500. break
  2501. visitor_data = try_get(
  2502. response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
  2503. continuation_contents = try_get(
  2504. response, lambda x: x['continuationContents'], dict)
  2505. if continuation_contents:
  2506. continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
  2507. if continuation_renderer:
  2508. for entry in self._playlist_entries(continuation_renderer):
  2509. yield entry
  2510. continuation = self._extract_continuation(continuation_renderer)
  2511. continue
  2512. continuation_renderer = continuation_contents.get('gridContinuation')
  2513. if continuation_renderer:
  2514. for entry in self._grid_entries(continuation_renderer):
  2515. yield entry
  2516. continuation = self._extract_continuation(continuation_renderer)
  2517. continue
  2518. continuation_renderer = continuation_contents.get('itemSectionContinuation')
  2519. if continuation_renderer:
  2520. for entry in self._post_thread_continuation_entries(continuation_renderer):
  2521. yield entry
  2522. continuation = self._extract_continuation(continuation_renderer)
  2523. continue
  2524. on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
  2525. continuation_items = try_get(
  2526. on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
  2527. if continuation_items:
  2528. continuation_item = continuation_items[0]
  2529. if not isinstance(continuation_item, dict):
  2530. continue
  2531. renderer = self._extract_grid_item_renderer(continuation_item)
  2532. if renderer:
  2533. grid_renderer = {'items': continuation_items}
  2534. for entry in self._grid_entries(grid_renderer):
  2535. yield entry
  2536. continuation = self._extract_continuation(grid_renderer)
  2537. continue
  2538. renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
  2539. if renderer:
  2540. video_list_renderer = {'contents': continuation_items}
  2541. for entry in self._playlist_entries(video_list_renderer):
  2542. yield entry
  2543. continuation = self._extract_continuation(video_list_renderer)
  2544. continue
  2545. renderer = continuation_item.get('backstagePostThreadRenderer')
  2546. if renderer:
  2547. continuation_renderer = {'contents': continuation_items}
  2548. for entry in self._post_thread_continuation_entries(continuation_renderer):
  2549. yield entry
  2550. continuation = self._extract_continuation(continuation_renderer)
  2551. continue
  2552. renderer = continuation_item.get('richItemRenderer')
  2553. if renderer:
  2554. for entry in self._rich_grid_entries(continuation_items):
  2555. yield entry
  2556. continuation = self._extract_continuation({'contents': continuation_items})
  2557. continue
  2558. break
  2559. @staticmethod
  2560. def _extract_selected_tab(tabs):
  2561. for tab in tabs:
  2562. if try_get(tab, lambda x: x['tabRenderer']['selected'], bool):
  2563. return tab['tabRenderer']
  2564. else:
  2565. raise ExtractorError('Unable to find selected tab')
  2566. @staticmethod
  2567. def _extract_uploader(data):
  2568. uploader = {}
  2569. sidebar_renderer = try_get(
  2570. data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
  2571. if sidebar_renderer:
  2572. for item in sidebar_renderer:
  2573. if not isinstance(item, dict):
  2574. continue
  2575. renderer = item.get('playlistSidebarSecondaryInfoRenderer')
  2576. if not isinstance(renderer, dict):
  2577. continue
  2578. owner = try_get(
  2579. renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
  2580. if owner:
  2581. uploader['uploader'] = owner.get('text')
  2582. uploader['uploader_id'] = try_get(
  2583. owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
  2584. uploader['uploader_url'] = urljoin(
  2585. 'https://www.youtube.com/',
  2586. try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
  2587. return uploader
  2588. @staticmethod
  2589. def _extract_alert(data):
  2590. alerts = []
  2591. for alert in try_get(data, lambda x: x['alerts'], list) or []:
  2592. if not isinstance(alert, dict):
  2593. continue
  2594. alert_text = try_get(
  2595. alert, lambda x: x['alertRenderer']['text'], dict)
  2596. if not alert_text:
  2597. continue
  2598. text = try_get(
  2599. alert_text,
  2600. (lambda x: x['simpleText'], lambda x: x['runs'][0]['text']),
  2601. compat_str)
  2602. if text:
  2603. alerts.append(text)
  2604. return '\n'.join(alerts)
  2605. def _extract_from_tabs(self, item_id, webpage, data, tabs):
  2606. selected_tab = self._extract_selected_tab(tabs)
  2607. renderer = try_get(
  2608. data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
  2609. playlist_id = item_id
  2610. title = description = None
  2611. if renderer:
  2612. channel_title = renderer.get('title') or item_id
  2613. tab_title = selected_tab.get('title')
  2614. title = channel_title or item_id
  2615. if tab_title:
  2616. title += ' - %s' % tab_title
  2617. description = renderer.get('description')
  2618. playlist_id = renderer.get('externalId')
  2619. else:
  2620. renderer = try_get(
  2621. data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
  2622. if renderer:
  2623. title = renderer.get('title')
  2624. else:
  2625. renderer = try_get(
  2626. data, lambda x: x['header']['hashtagHeaderRenderer'], dict)
  2627. if renderer:
  2628. title = try_get(renderer, lambda x: x['hashtag']['simpleText'])
  2629. playlist = self.playlist_result(
  2630. self._entries(selected_tab, item_id, webpage),
  2631. playlist_id=playlist_id, playlist_title=title,
  2632. playlist_description=description)
  2633. playlist.update(self._extract_uploader(data))
  2634. return playlist
  2635. def _extract_from_playlist(self, item_id, url, data, playlist):
  2636. title = playlist.get('title') or try_get(
  2637. data, lambda x: x['titleText']['simpleText'], compat_str)
  2638. playlist_id = playlist.get('playlistId') or item_id
  2639. # Inline playlist rendition continuation does not always work
  2640. # at Youtube side, so delegating regular tab-based playlist URL
  2641. # processing whenever possible.
  2642. playlist_url = urljoin(url, try_get(
  2643. playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  2644. compat_str))
  2645. if playlist_url and playlist_url != url:
  2646. return self.url_result(
  2647. playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  2648. video_title=title)
  2649. return self.playlist_result(
  2650. self._playlist_entries(playlist), playlist_id=playlist_id,
  2651. playlist_title=title)
  2652. def _extract_identity_token(self, ytcfg, webpage):
  2653. if ytcfg:
  2654. token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
  2655. if token:
  2656. return token
  2657. return self._search_regex(
  2658. r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
  2659. 'identity token', default=None)
  2660. def _real_extract(self, url):
  2661. item_id = self._match_id(url)
  2662. url = compat_urlparse.urlunparse(
  2663. compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
  2664. # Handle both video/playlist URLs
  2665. qs = parse_qs(url)
  2666. video_id = qs.get('v', [None])[0]
  2667. playlist_id = qs.get('list', [None])[0]
  2668. if video_id and playlist_id:
  2669. if self._downloader.params.get('noplaylist'):
  2670. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2671. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  2672. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2673. webpage = self._download_webpage(url, item_id)
  2674. data = self._extract_yt_initial_data(item_id, webpage)
  2675. tabs = try_get(
  2676. data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
  2677. if tabs:
  2678. return self._extract_from_tabs(item_id, webpage, data, tabs)
  2679. playlist = try_get(
  2680. data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
  2681. if playlist:
  2682. return self._extract_from_playlist(item_id, url, data, playlist)
  2683. # Fallback to video extraction if no playlist alike page is recognized.
  2684. # First check for the current video then try the v attribute of URL query.
  2685. video_id = try_get(
  2686. data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
  2687. compat_str) or video_id
  2688. if video_id:
  2689. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  2690. # Capture and output alerts
  2691. alert = self._extract_alert(data)
  2692. if alert:
  2693. raise ExtractorError(alert, expected=True)
  2694. # Failed to recognize
  2695. raise ExtractorError('Unable to recognize tab page')
  2696. class YoutubePlaylistIE(InfoExtractor):
  2697. IE_DESC = 'YouTube.com playlists'
  2698. _VALID_URL = r'''(?x)(?:
  2699. (?:https?://)?
  2700. (?:\w+\.)?
  2701. (?:
  2702. (?:
  2703. youtube(?:kids)?\.com|
  2704. invidio\.us
  2705. )
  2706. /.*?\?.*?\blist=
  2707. )?
  2708. (?P<id>%(playlist_id)s)
  2709. )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2710. IE_NAME = 'youtube:playlist'
  2711. _TESTS = [{
  2712. 'note': 'issue #673',
  2713. 'url': 'PLBB231211A4F62143',
  2714. 'info_dict': {
  2715. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2716. 'id': 'PLBB231211A4F62143',
  2717. 'uploader': 'Wickydoo',
  2718. 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
  2719. },
  2720. 'playlist_mincount': 29,
  2721. }, {
  2722. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2723. 'info_dict': {
  2724. 'title': 'YDL_safe_search',
  2725. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2726. },
  2727. 'playlist_count': 2,
  2728. 'skip': 'This playlist is private',
  2729. }, {
  2730. 'note': 'embedded',
  2731. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2732. 'playlist_count': 4,
  2733. 'info_dict': {
  2734. 'title': 'JODA15',
  2735. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2736. 'uploader': 'milan',
  2737. 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  2738. }
  2739. }, {
  2740. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2741. 'playlist_mincount': 982,
  2742. 'info_dict': {
  2743. 'title': '2018 Chinese New Singles (11/6 updated)',
  2744. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2745. 'uploader': 'LBK',
  2746. 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
  2747. }
  2748. }, {
  2749. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2750. 'only_matching': True,
  2751. }, {
  2752. # music album playlist
  2753. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2754. 'only_matching': True,
  2755. }]
  2756. @classmethod
  2757. def suitable(cls, url):
  2758. if YoutubeTabIE.suitable(url):
  2759. return False
  2760. # Hack for lazy extractors until more generic solution is implemented
  2761. # (see #28780)
  2762. from .youtube import parse_qs
  2763. qs = parse_qs(url)
  2764. if qs.get('v', [None])[0]:
  2765. return False
  2766. return super(YoutubePlaylistIE, cls).suitable(url)
  2767. def _real_extract(self, url):
  2768. playlist_id = self._match_id(url)
  2769. qs = parse_qs(url)
  2770. if not qs:
  2771. qs = {'list': playlist_id}
  2772. return self.url_result(
  2773. update_url_query('https://www.youtube.com/playlist', qs),
  2774. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  2775. class YoutubeYtBeIE(InfoExtractor):
  2776. _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}
  2777. _TESTS = [{
  2778. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2779. 'info_dict': {
  2780. 'id': 'yeWKywCrFtk',
  2781. 'ext': 'mp4',
  2782. 'title': 'Small Scale Baler and Braiding Rugs',
  2783. 'uploader': 'Backus-Page House Museum',
  2784. 'uploader_id': 'backuspagemuseum',
  2785. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2786. 'upload_date': '20161008',
  2787. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2788. 'categories': ['Nonprofits & Activism'],
  2789. 'tags': list,
  2790. 'like_count': int,
  2791. 'dislike_count': int,
  2792. },
  2793. 'params': {
  2794. 'noplaylist': True,
  2795. 'skip_download': True,
  2796. },
  2797. }, {
  2798. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  2799. 'only_matching': True,
  2800. }]
  2801. def _real_extract(self, url):
  2802. mobj = re.match(self._VALID_URL, url)
  2803. video_id = mobj.group('id')
  2804. playlist_id = mobj.group('playlist_id')
  2805. return self.url_result(
  2806. update_url_query('https://www.youtube.com/watch', {
  2807. 'v': video_id,
  2808. 'list': playlist_id,
  2809. 'feature': 'youtu.be',
  2810. }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  2811. class YoutubeYtUserIE(InfoExtractor):
  2812. _VALID_URL = r'ytuser:(?P<id>.+)'
  2813. _TESTS = [{
  2814. 'url': 'ytuser:phihag',
  2815. 'only_matching': True,
  2816. }]
  2817. def _real_extract(self, url):
  2818. user_id = self._match_id(url)
  2819. return self.url_result(
  2820. 'https://www.youtube.com/user/%s' % user_id,
  2821. ie=YoutubeTabIE.ie_key(), video_id=user_id)
  2822. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2823. IE_NAME = 'youtube:favorites'
  2824. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2825. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2826. _LOGIN_REQUIRED = True
  2827. _TESTS = [{
  2828. 'url': ':ytfav',
  2829. 'only_matching': True,
  2830. }, {
  2831. 'url': ':ytfavorites',
  2832. 'only_matching': True,
  2833. }]
  2834. def _real_extract(self, url):
  2835. return self.url_result(
  2836. 'https://www.youtube.com/playlist?list=LL',
  2837. ie=YoutubeTabIE.ie_key())
  2838. class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
  2839. IE_DESC = 'YouTube.com searches'
  2840. # there doesn't appear to be a real limit, for example if you search for
  2841. # 'python' you get more than 8.000.000 results
  2842. _MAX_RESULTS = float('inf')
  2843. IE_NAME = 'youtube:search'
  2844. _SEARCH_KEY = 'ytsearch'
  2845. _SEARCH_PARAMS = None
  2846. _TESTS = []
  2847. def _entries(self, query, n):
  2848. data = {
  2849. 'context': {
  2850. 'client': {
  2851. 'clientName': 'WEB',
  2852. 'clientVersion': '2.20201021.03.00',
  2853. }
  2854. },
  2855. 'query': query,
  2856. }
  2857. if self._SEARCH_PARAMS:
  2858. data['params'] = self._SEARCH_PARAMS
  2859. total = 0
  2860. for page_num in itertools.count(1):
  2861. search = self._download_json(
  2862. 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  2863. video_id='query "%s"' % query,
  2864. note='Downloading page %s' % page_num,
  2865. errnote='Unable to download API page', fatal=False,
  2866. data=json.dumps(data).encode('utf8'),
  2867. headers={'content-type': 'application/json'})
  2868. if not search:
  2869. break
  2870. slr_contents = try_get(
  2871. search,
  2872. (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
  2873. lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
  2874. list)
  2875. if not slr_contents:
  2876. break
  2877. for slr_content in slr_contents:
  2878. isr_contents = try_get(
  2879. slr_content,
  2880. lambda x: x['itemSectionRenderer']['contents'],
  2881. list)
  2882. if not isr_contents:
  2883. continue
  2884. for content in isr_contents:
  2885. if not isinstance(content, dict):
  2886. continue
  2887. video = content.get('videoRenderer')
  2888. if not isinstance(video, dict):
  2889. continue
  2890. video_id = video.get('videoId')
  2891. if not video_id:
  2892. continue
  2893. yield self._extract_video(video)
  2894. total += 1
  2895. if total == n:
  2896. return
  2897. token = try_get(
  2898. slr_contents,
  2899. lambda x: x[-1]['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
  2900. compat_str)
  2901. if not token:
  2902. break
  2903. data['continuation'] = token
  2904. def _get_n_results(self, query, n):
  2905. """Get a specified number of results for a query"""
  2906. return self.playlist_result(self._entries(query, n), query)
  2907. class YoutubeSearchDateIE(YoutubeSearchIE):
  2908. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  2909. _SEARCH_KEY = 'ytsearchdate'
  2910. IE_DESC = 'YouTube.com searches, newest videos first'
  2911. _SEARCH_PARAMS = 'CAI%3D'
  2912. r"""
  2913. class YoutubeSearchURLIE(YoutubeSearchIE):
  2914. IE_DESC = 'YouTube.com search URLs'
  2915. IE_NAME = 'youtube:search_url'
  2916. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  2917. _TESTS = [{
  2918. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  2919. 'playlist_mincount': 5,
  2920. 'info_dict': {
  2921. 'title': 'youtube-dl test video',
  2922. }
  2923. }, {
  2924. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  2925. 'only_matching': True,
  2926. }]
  2927. def _real_extract(self, url):
  2928. mobj = re.match(self._VALID_URL, url)
  2929. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  2930. webpage = self._download_webpage(url, query)
  2931. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  2932. """
  2933. class YoutubeFeedsInfoExtractor(YoutubeTabIE):
  2934. """
  2935. Base class for feed extractors
  2936. Subclasses must define the _FEED_NAME property.
  2937. """
  2938. _LOGIN_REQUIRED = True
  2939. @property
  2940. def IE_NAME(self):
  2941. return 'youtube:%s' % self._FEED_NAME
  2942. def _real_initialize(self):
  2943. self._login()
  2944. def _real_extract(self, url):
  2945. return self.url_result(
  2946. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  2947. ie=YoutubeTabIE.ie_key())
  2948. class YoutubeWatchLaterIE(InfoExtractor):
  2949. IE_NAME = 'youtube:watchlater'
  2950. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  2951. _VALID_URL = r':ytwatchlater'
  2952. _TESTS = [{
  2953. 'url': ':ytwatchlater',
  2954. 'only_matching': True,
  2955. }]
  2956. def _real_extract(self, url):
  2957. return self.url_result(
  2958. 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
  2959. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2960. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2961. _VALID_URL = r':ytrec(?:ommended)?'
  2962. _FEED_NAME = 'recommended'
  2963. _TESTS = [{
  2964. 'url': ':ytrec',
  2965. 'only_matching': True,
  2966. }, {
  2967. 'url': ':ytrecommended',
  2968. 'only_matching': True,
  2969. }]
  2970. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2971. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2972. _VALID_URL = r':ytsubs(?:criptions)?'
  2973. _FEED_NAME = 'subscriptions'
  2974. _TESTS = [{
  2975. 'url': ':ytsubs',
  2976. 'only_matching': True,
  2977. }, {
  2978. 'url': ':ytsubscriptions',
  2979. 'only_matching': True,
  2980. }]
  2981. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2982. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2983. _VALID_URL = r':ythistory'
  2984. _FEED_NAME = 'history'
  2985. _TESTS = [{
  2986. 'url': ':ythistory',
  2987. 'only_matching': True,
  2988. }]
  2989. class YoutubeTruncatedURLIE(InfoExtractor):
  2990. IE_NAME = 'youtube:truncated_url'
  2991. IE_DESC = False # Do not list
  2992. _VALID_URL = r'''(?x)
  2993. (?:https?://)?
  2994. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  2995. (?:watch\?(?:
  2996. feature=[a-z_]+|
  2997. annotation_id=annotation_[^&]+|
  2998. x-yt-cl=[0-9]+|
  2999. hl=[^&]*|
  3000. t=[0-9]+
  3001. )?
  3002. |
  3003. attribution_link\?a=[^&]+
  3004. )
  3005. $
  3006. '''
  3007. _TESTS = [{
  3008. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  3009. 'only_matching': True,
  3010. }, {
  3011. 'url': 'https://www.youtube.com/watch?',
  3012. 'only_matching': True,
  3013. }, {
  3014. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  3015. 'only_matching': True,
  3016. }, {
  3017. 'url': 'https://www.youtube.com/watch?feature=foo',
  3018. 'only_matching': True,
  3019. }, {
  3020. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  3021. 'only_matching': True,
  3022. }, {
  3023. 'url': 'https://www.youtube.com/watch?t=2372',
  3024. 'only_matching': True,
  3025. }]
  3026. def _real_extract(self, url):
  3027. raise ExtractorError(
  3028. 'Did you forget to quote the URL? Remember that & is a meta '
  3029. 'character in most shells, so you want to put the URL in quotes, '
  3030. 'like youtube-dl '
  3031. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  3032. ' or simply youtube-dl BaW_jenozKc .',
  3033. expected=True)
  3034. class YoutubeTruncatedIDIE(InfoExtractor):
  3035. IE_NAME = 'youtube:truncated_id'
  3036. IE_DESC = False # Do not list
  3037. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  3038. _TESTS = [{
  3039. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  3040. 'only_matching': True,
  3041. }]
  3042. def _real_extract(self, url):
  3043. video_id = self._match_id(url)
  3044. raise ExtractorError(
  3045. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  3046. expected=True)