youtube.py 130 KB

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