youtube.py 137 KB

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