youtube.py 132 KB

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