youtube.py 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323
  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 time
  9. import traceback
  10. from .common import InfoExtractor, SearchInfoExtractor
  11. from ..jsinterp import JSInterpreter
  12. from ..swfinterp import SWFInterpreter
  13. from ..compat import (
  14. compat_chr,
  15. compat_HTTPError,
  16. compat_kwargs,
  17. compat_parse_qs,
  18. compat_urllib_parse_unquote,
  19. compat_urllib_parse_unquote_plus,
  20. compat_urllib_parse_urlencode,
  21. compat_urllib_parse_urlparse,
  22. compat_urlparse,
  23. compat_str,
  24. )
  25. from ..utils import (
  26. bool_or_none,
  27. clean_html,
  28. error_to_compat_str,
  29. extract_attributes,
  30. ExtractorError,
  31. float_or_none,
  32. get_element_by_attribute,
  33. get_element_by_id,
  34. int_or_none,
  35. mimetype2ext,
  36. orderedSet,
  37. parse_codecs,
  38. parse_duration,
  39. remove_quotes,
  40. remove_start,
  41. smuggle_url,
  42. str_or_none,
  43. str_to_int,
  44. try_get,
  45. unescapeHTML,
  46. unified_strdate,
  47. unsmuggle_url,
  48. uppercase_escape,
  49. url_or_none,
  50. urlencode_postdata,
  51. )
  52. class YoutubeBaseInfoExtractor(InfoExtractor):
  53. """Provide base functions for Youtube extractors"""
  54. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  55. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  56. _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
  57. _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
  58. _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
  59. _NETRC_MACHINE = 'youtube'
  60. # If True it will raise an error if no login info is provided
  61. _LOGIN_REQUIRED = False
  62. _PLAYLIST_ID_RE = r'(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}'
  63. def _set_language(self):
  64. self._set_cookie(
  65. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  66. # YouTube sets the expire time to about two months
  67. expire_time=time.time() + 2 * 30 * 24 * 3600)
  68. def _ids_to_results(self, ids):
  69. return [
  70. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  71. for vid_id in ids]
  72. def _login(self):
  73. """
  74. Attempt to log in to YouTube.
  75. True is returned if successful or skipped.
  76. False is returned if login failed.
  77. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  78. """
  79. username, password = self._get_login_info()
  80. # No authentication to be performed
  81. if username is None:
  82. if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
  83. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  84. return True
  85. login_page = self._download_webpage(
  86. self._LOGIN_URL, None,
  87. note='Downloading login page',
  88. errnote='unable to fetch login page', fatal=False)
  89. if login_page is False:
  90. return
  91. login_form = self._hidden_inputs(login_page)
  92. def req(url, f_req, note, errnote):
  93. data = login_form.copy()
  94. data.update({
  95. 'pstMsg': 1,
  96. 'checkConnection': 'youtube',
  97. 'checkedDomains': 'youtube',
  98. 'hl': 'en',
  99. 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
  100. 'f.req': json.dumps(f_req),
  101. 'flowName': 'GlifWebSignIn',
  102. 'flowEntry': 'ServiceLogin',
  103. # TODO: reverse actual botguard identifier generation algo
  104. 'bgRequest': '["identifier",""]',
  105. })
  106. return self._download_json(
  107. url, None, note=note, errnote=errnote,
  108. transform_source=lambda s: re.sub(r'^[^[]*', '', s),
  109. fatal=False,
  110. data=urlencode_postdata(data), headers={
  111. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  112. 'Google-Accounts-XSRF': 1,
  113. })
  114. def warn(message):
  115. self._downloader.report_warning(message)
  116. lookup_req = [
  117. username,
  118. None, [], None, 'US', None, None, 2, False, True,
  119. [
  120. None, None,
  121. [2, 1, None, 1,
  122. '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',
  123. None, [], 4],
  124. 1, [None, None, []], None, None, None, True
  125. ],
  126. username,
  127. ]
  128. lookup_results = req(
  129. self._LOOKUP_URL, lookup_req,
  130. 'Looking up account info', 'Unable to look up account info')
  131. if lookup_results is False:
  132. return False
  133. user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
  134. if not user_hash:
  135. warn('Unable to extract user hash')
  136. return False
  137. challenge_req = [
  138. user_hash,
  139. None, 1, None, [1, None, None, None, [password, None, True]],
  140. [
  141. 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],
  142. 1, [None, None, []], None, None, None, True
  143. ]]
  144. challenge_results = req(
  145. self._CHALLENGE_URL, challenge_req,
  146. 'Logging in', 'Unable to log in')
  147. if challenge_results is False:
  148. return
  149. login_res = try_get(challenge_results, lambda x: x[0][5], list)
  150. if login_res:
  151. login_msg = try_get(login_res, lambda x: x[5], compat_str)
  152. warn(
  153. 'Unable to login: %s' % 'Invalid password'
  154. if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
  155. return False
  156. res = try_get(challenge_results, lambda x: x[0][-1], list)
  157. if not res:
  158. warn('Unable to extract result entry')
  159. return False
  160. login_challenge = try_get(res, lambda x: x[0][0], list)
  161. if login_challenge:
  162. challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
  163. if challenge_str == 'TWO_STEP_VERIFICATION':
  164. # SEND_SUCCESS - TFA code has been successfully sent to phone
  165. # QUOTA_EXCEEDED - reached the limit of TFA codes
  166. status = try_get(login_challenge, lambda x: x[5], compat_str)
  167. if status == 'QUOTA_EXCEEDED':
  168. warn('Exceeded the limit of TFA codes, try later')
  169. return False
  170. tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
  171. if not tl:
  172. warn('Unable to extract TL')
  173. return False
  174. tfa_code = self._get_tfa_info('2-step verification code')
  175. if not tfa_code:
  176. warn(
  177. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  178. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  179. return False
  180. tfa_code = remove_start(tfa_code, 'G-')
  181. tfa_req = [
  182. user_hash, None, 2, None,
  183. [
  184. 9, None, None, None, None, None, None, None,
  185. [None, tfa_code, True, 2]
  186. ]]
  187. tfa_results = req(
  188. self._TFA_URL.format(tl), tfa_req,
  189. 'Submitting TFA code', 'Unable to submit TFA code')
  190. if tfa_results is False:
  191. return False
  192. tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
  193. if tfa_res:
  194. tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
  195. warn(
  196. 'Unable to finish TFA: %s' % 'Invalid TFA code'
  197. if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
  198. return False
  199. check_cookie_url = try_get(
  200. tfa_results, lambda x: x[0][-1][2], compat_str)
  201. else:
  202. CHALLENGES = {
  203. 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
  204. 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
  205. 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
  206. }
  207. challenge = CHALLENGES.get(
  208. challenge_str,
  209. '%s returned error %s.' % (self.IE_NAME, challenge_str))
  210. warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
  211. return False
  212. else:
  213. check_cookie_url = try_get(res, lambda x: x[2], compat_str)
  214. if not check_cookie_url:
  215. warn('Unable to extract CheckCookie URL')
  216. return False
  217. check_cookie_results = self._download_webpage(
  218. check_cookie_url, None, 'Checking cookie', fatal=False)
  219. if check_cookie_results is False:
  220. return False
  221. if 'https://myaccount.google.com/' not in check_cookie_results:
  222. warn('Unable to log in')
  223. return False
  224. return True
  225. def _download_webpage_handle(self, *args, **kwargs):
  226. query = kwargs.get('query', {}).copy()
  227. query['disable_polymer'] = 'true'
  228. kwargs['query'] = query
  229. return super(YoutubeBaseInfoExtractor, self)._download_webpage_handle(
  230. *args, **compat_kwargs(kwargs))
  231. def _real_initialize(self):
  232. if self._downloader is None:
  233. return
  234. self._set_language()
  235. if not self._login():
  236. return
  237. class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
  238. # Extract entries from page with "Load more" button
  239. def _entries(self, page, playlist_id):
  240. more_widget_html = content_html = page
  241. for page_num in itertools.count(1):
  242. for entry in self._process_page(content_html):
  243. yield entry
  244. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  245. if not mobj:
  246. break
  247. count = 0
  248. retries = 3
  249. while count <= retries:
  250. try:
  251. # Downloading page may result in intermittent 5xx HTTP error
  252. # that is usually worked around with a retry
  253. more = self._download_json(
  254. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  255. 'Downloading page #%s%s'
  256. % (page_num, ' (retry #%d)' % count if count else ''),
  257. transform_source=uppercase_escape)
  258. break
  259. except ExtractorError as e:
  260. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  261. count += 1
  262. if count <= retries:
  263. continue
  264. raise
  265. content_html = more['content_html']
  266. if not content_html.strip():
  267. # Some webpages show a "Load more" button but they don't
  268. # have more videos
  269. break
  270. more_widget_html = more['load_more_widget_html']
  271. class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  272. def _process_page(self, content):
  273. for video_id, video_title in self.extract_videos_from_page(content):
  274. yield self.url_result(video_id, 'Youtube', video_id, video_title)
  275. def extract_videos_from_page_impl(self, video_re, page, ids_in_page, titles_in_page):
  276. for mobj in re.finditer(video_re, page):
  277. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  278. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  279. continue
  280. video_id = mobj.group('id')
  281. video_title = unescapeHTML(
  282. mobj.group('title')) if 'title' in mobj.groupdict() else None
  283. if video_title:
  284. video_title = video_title.strip()
  285. if video_title == '► Play all':
  286. video_title = None
  287. try:
  288. idx = ids_in_page.index(video_id)
  289. if video_title and not titles_in_page[idx]:
  290. titles_in_page[idx] = video_title
  291. except ValueError:
  292. ids_in_page.append(video_id)
  293. titles_in_page.append(video_title)
  294. def extract_videos_from_page(self, page):
  295. ids_in_page = []
  296. titles_in_page = []
  297. self.extract_videos_from_page_impl(
  298. self._VIDEO_RE, page, ids_in_page, titles_in_page)
  299. return zip(ids_in_page, titles_in_page)
  300. class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  301. def _process_page(self, content):
  302. for playlist_id in orderedSet(re.findall(
  303. r'<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*><a[^>]+href="/?playlist\?list=([0-9A-Za-z-_]{10,})"',
  304. content)):
  305. yield self.url_result(
  306. 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
  307. def _real_extract(self, url):
  308. playlist_id = self._match_id(url)
  309. webpage = self._download_webpage(url, playlist_id)
  310. title = self._og_search_title(webpage, fatal=False)
  311. return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
  312. class YoutubeIE(YoutubeBaseInfoExtractor):
  313. IE_DESC = 'YouTube.com'
  314. _VALID_URL = r"""(?x)^
  315. (
  316. (?:https?://|//) # http(s):// or protocol-independent URL
  317. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com/|
  318. (?:www\.)?deturl\.com/www\.youtube\.com/|
  319. (?:www\.)?pwnyoutube\.com/|
  320. (?:www\.)?hooktube\.com/|
  321. (?:www\.)?yourepeat\.com/|
  322. tube\.majestyc\.net/|
  323. # Invidious instances taken from https://github.com/omarroth/invidious/wiki/Invidious-Instances
  324. (?:(?:www|dev)\.)?invidio\.us/|
  325. (?:(?:www|no)\.)?invidiou\.sh/|
  326. (?:(?:www|fi|de)\.)?invidious\.snopyta\.org/|
  327. (?:www\.)?invidious\.kabi\.tk/|
  328. (?:www\.)?invidious\.13ad\.de/|
  329. (?:www\.)?invidious\.mastodon\.host/|
  330. (?:www\.)?invidious\.nixnet\.xyz/|
  331. (?:www\.)?invidious\.drycat\.fr/|
  332. (?:www\.)?tube\.poal\.co/|
  333. (?:www\.)?vid\.wxzm\.sx/|
  334. (?:www\.)?yewtu\.be/|
  335. (?:www\.)?yt\.elukerio\.org/|
  336. (?:www\.)?yt\.lelux\.fi/|
  337. (?:www\.)?invidious\.ggc-project\.de/|
  338. (?:www\.)?yt\.maisputain\.ovh/|
  339. (?:www\.)?invidious\.13ad\.de/|
  340. (?:www\.)?invidious\.toot\.koeln/|
  341. (?:www\.)?invidious\.fdn\.fr/|
  342. (?:www\.)?watch\.nettohikari\.com/|
  343. (?:www\.)?kgg2m7yk5aybusll\.onion/|
  344. (?:www\.)?qklhadlycap4cnod\.onion/|
  345. (?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion/|
  346. (?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion/|
  347. (?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion/|
  348. (?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion/|
  349. (?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p/|
  350. (?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion/|
  351. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  352. (?:.*?\#/)? # handle anchor (#/) redirect urls
  353. (?: # the various things that can precede the ID:
  354. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  355. |(?: # or the v= param in all its forms
  356. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  357. (?:\?|\#!?) # the params delimiter ? or # or #!
  358. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  359. v=
  360. )
  361. ))
  362. |(?:
  363. youtu\.be| # just youtu.be/xxxx
  364. vid\.plus| # or vid.plus/xxxx
  365. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  366. )/
  367. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  368. )
  369. )? # all until now is optional -> you can pass the naked ID
  370. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  371. (?!.*?\blist=
  372. (?:
  373. %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
  374. WL # WL are handled by the watch later IE
  375. )
  376. )
  377. (?(1).+)? # if we found the ID, everything can follow
  378. $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  379. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  380. _PLAYER_INFO_RE = (
  381. r'/(?P<id>[a-zA-Z0-9_-]{8,})/player_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?/base\.(?P<ext>[a-z]+)$',
  382. r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.(?P<ext>[a-z]+)$',
  383. )
  384. _formats = {
  385. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  386. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  387. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  388. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  389. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  390. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  391. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  392. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  393. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  394. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  395. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  396. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  397. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  398. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  399. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  400. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  401. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  402. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  403. # 3D videos
  404. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  405. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  406. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  407. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  408. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  409. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  410. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  411. # Apple HTTP Live Streaming
  412. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  413. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  414. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  415. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  416. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  417. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  418. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  419. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  420. # DASH mp4 video
  421. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  422. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  423. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  424. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  425. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  426. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  427. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  428. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  429. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  430. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  431. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  432. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  433. # Dash mp4 audio
  434. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  435. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  436. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  437. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  438. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  439. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  440. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  441. # Dash webm
  442. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  443. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  444. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  445. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  446. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  447. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  448. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  449. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  450. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  451. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  452. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  453. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  454. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  455. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  456. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  457. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  458. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  459. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  460. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  461. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  462. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  463. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  464. # Dash webm audio
  465. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  466. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  467. # Dash webm audio with opus inside
  468. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  469. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  470. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  471. # RTMP (unnamed)
  472. '_rtmp': {'protocol': 'rtmp'},
  473. # av01 video only formats sometimes served with "unknown" codecs
  474. '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  475. '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  476. '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  477. '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  478. }
  479. _SUBTITLE_FORMATS = ('srv1', 'srv2', 'srv3', 'ttml', 'vtt')
  480. _GEO_BYPASS = False
  481. IE_NAME = 'youtube'
  482. _TESTS = [
  483. {
  484. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  485. 'info_dict': {
  486. 'id': 'BaW_jenozKc',
  487. 'ext': 'mp4',
  488. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  489. 'uploader': 'Philipp Hagemeister',
  490. 'uploader_id': 'phihag',
  491. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  492. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  493. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  494. 'upload_date': '20121002',
  495. '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 .',
  496. 'categories': ['Science & Technology'],
  497. 'tags': ['youtube-dl'],
  498. 'duration': 10,
  499. 'view_count': int,
  500. 'like_count': int,
  501. 'dislike_count': int,
  502. 'start_time': 1,
  503. 'end_time': 9,
  504. }
  505. },
  506. {
  507. 'url': 'https://www.youtube.com/watch?v=UxxajLWwzqY',
  508. 'note': 'Test generic use_cipher_signature video (#897)',
  509. 'info_dict': {
  510. 'id': 'UxxajLWwzqY',
  511. 'ext': 'mp4',
  512. 'upload_date': '20120506',
  513. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  514. 'alt_title': 'I Love It (feat. Charli XCX)',
  515. 'description': 'md5:19a2f98d9032b9311e686ed039564f63',
  516. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  517. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  518. 'iconic ep', 'iconic', 'love', 'it'],
  519. 'duration': 180,
  520. 'uploader': 'Icona Pop',
  521. 'uploader_id': 'IconaPop',
  522. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IconaPop',
  523. 'creator': 'Icona Pop',
  524. 'track': 'I Love It (feat. Charli XCX)',
  525. 'artist': 'Icona Pop',
  526. }
  527. },
  528. {
  529. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  530. 'note': 'Test VEVO video with age protection (#956)',
  531. 'info_dict': {
  532. 'id': '07FYdnEawAQ',
  533. 'ext': 'mp4',
  534. 'upload_date': '20130703',
  535. 'title': 'Justin Timberlake - Tunnel Vision (Official Music Video) (Explicit)',
  536. 'alt_title': 'Tunnel Vision',
  537. 'description': 'md5:07dab3356cde4199048e4c7cd93471e1',
  538. 'duration': 419,
  539. 'uploader': 'justintimberlakeVEVO',
  540. 'uploader_id': 'justintimberlakeVEVO',
  541. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/justintimberlakeVEVO',
  542. 'creator': 'Justin Timberlake',
  543. 'track': 'Tunnel Vision',
  544. 'artist': 'Justin Timberlake',
  545. 'age_limit': 18,
  546. }
  547. },
  548. {
  549. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  550. 'note': 'Embed-only video (#1746)',
  551. 'info_dict': {
  552. 'id': 'yZIXLfi8CZQ',
  553. 'ext': 'mp4',
  554. 'upload_date': '20120608',
  555. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  556. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  557. 'uploader': 'SET India',
  558. 'uploader_id': 'setindia',
  559. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
  560. 'age_limit': 18,
  561. }
  562. },
  563. {
  564. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
  565. 'note': 'Use the first video ID in the URL',
  566. 'info_dict': {
  567. 'id': 'BaW_jenozKc',
  568. 'ext': 'mp4',
  569. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  570. 'uploader': 'Philipp Hagemeister',
  571. 'uploader_id': 'phihag',
  572. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  573. 'upload_date': '20121002',
  574. '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 .',
  575. 'categories': ['Science & Technology'],
  576. 'tags': ['youtube-dl'],
  577. 'duration': 10,
  578. 'view_count': int,
  579. 'like_count': int,
  580. 'dislike_count': int,
  581. },
  582. 'params': {
  583. 'skip_download': True,
  584. },
  585. },
  586. {
  587. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  588. 'note': '256k DASH audio (format 141) via DASH manifest',
  589. 'info_dict': {
  590. 'id': 'a9LDPn-MO4I',
  591. 'ext': 'm4a',
  592. 'upload_date': '20121002',
  593. 'uploader_id': '8KVIDEO',
  594. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  595. 'description': '',
  596. 'uploader': '8KVIDEO',
  597. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  598. },
  599. 'params': {
  600. 'youtube_include_dash_manifest': True,
  601. 'format': '141',
  602. },
  603. 'skip': 'format 141 not served anymore',
  604. },
  605. # DASH manifest with encrypted signature
  606. {
  607. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  608. 'info_dict': {
  609. 'id': 'IB3lcPjvWLA',
  610. 'ext': 'm4a',
  611. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  612. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  613. 'duration': 244,
  614. 'uploader': 'AfrojackVEVO',
  615. 'uploader_id': 'AfrojackVEVO',
  616. 'upload_date': '20131011',
  617. },
  618. 'params': {
  619. 'youtube_include_dash_manifest': True,
  620. 'format': '141/bestaudio[ext=m4a]',
  621. },
  622. },
  623. # JS player signature function name containing $
  624. {
  625. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  626. 'info_dict': {
  627. 'id': 'nfWlot6h_JM',
  628. 'ext': 'm4a',
  629. 'title': 'Taylor Swift - Shake It Off',
  630. 'description': 'md5:307195cd21ff7fa352270fe884570ef0',
  631. 'duration': 242,
  632. 'uploader': 'TaylorSwiftVEVO',
  633. 'uploader_id': 'TaylorSwiftVEVO',
  634. 'upload_date': '20140818',
  635. },
  636. 'params': {
  637. 'youtube_include_dash_manifest': True,
  638. 'format': '141/bestaudio[ext=m4a]',
  639. },
  640. },
  641. # Controversy video
  642. {
  643. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  644. 'info_dict': {
  645. 'id': 'T4XJQO3qol8',
  646. 'ext': 'mp4',
  647. 'duration': 219,
  648. 'upload_date': '20100909',
  649. 'uploader': 'Amazing Atheist',
  650. 'uploader_id': 'TheAmazingAtheist',
  651. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
  652. 'title': 'Burning Everyone\'s Koran',
  653. 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms\n\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',
  654. }
  655. },
  656. # Normal age-gate video (No vevo, embed allowed)
  657. {
  658. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  659. 'info_dict': {
  660. 'id': 'HtVdAasjOgU',
  661. 'ext': 'mp4',
  662. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  663. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  664. 'duration': 142,
  665. 'uploader': 'The Witcher',
  666. 'uploader_id': 'WitcherGame',
  667. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
  668. 'upload_date': '20140605',
  669. 'age_limit': 18,
  670. },
  671. },
  672. # Age-gate video with encrypted signature
  673. {
  674. 'url': 'https://www.youtube.com/watch?v=6kLq3WMV1nU',
  675. 'info_dict': {
  676. 'id': '6kLq3WMV1nU',
  677. 'ext': 'mp4',
  678. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  679. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  680. 'duration': 246,
  681. 'uploader': 'LloydVEVO',
  682. 'uploader_id': 'LloydVEVO',
  683. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/LloydVEVO',
  684. 'upload_date': '20110629',
  685. 'age_limit': 18,
  686. },
  687. },
  688. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  689. # YouTube Red ad is not captured for creator
  690. {
  691. 'url': '__2ABJjxzNo',
  692. 'info_dict': {
  693. 'id': '__2ABJjxzNo',
  694. 'ext': 'mp4',
  695. 'duration': 266,
  696. 'upload_date': '20100430',
  697. 'uploader_id': 'deadmau5',
  698. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
  699. 'creator': 'Dada Life, deadmau5',
  700. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  701. 'uploader': 'deadmau5',
  702. 'title': 'Deadmau5 - Some Chords (HD)',
  703. 'alt_title': 'This Machine Kills Some Chords',
  704. },
  705. 'expected_warnings': [
  706. 'DASH manifest missing',
  707. ]
  708. },
  709. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  710. {
  711. 'url': 'lqQg6PlCWgI',
  712. 'info_dict': {
  713. 'id': 'lqQg6PlCWgI',
  714. 'ext': 'mp4',
  715. 'duration': 6085,
  716. 'upload_date': '20150827',
  717. 'uploader_id': 'olympic',
  718. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
  719. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  720. 'uploader': 'Olympic',
  721. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  722. },
  723. 'params': {
  724. 'skip_download': 'requires avconv',
  725. }
  726. },
  727. # Non-square pixels
  728. {
  729. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  730. 'info_dict': {
  731. 'id': '_b-2C3KPAM0',
  732. 'ext': 'mp4',
  733. 'stretched_ratio': 16 / 9.,
  734. 'duration': 85,
  735. 'upload_date': '20110310',
  736. 'uploader_id': 'AllenMeow',
  737. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
  738. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  739. 'uploader': '孫ᄋᄅ',
  740. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  741. },
  742. },
  743. # url_encoded_fmt_stream_map is empty string
  744. {
  745. 'url': 'qEJwOuvDf7I',
  746. 'info_dict': {
  747. 'id': 'qEJwOuvDf7I',
  748. 'ext': 'webm',
  749. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  750. 'description': '',
  751. 'upload_date': '20150404',
  752. 'uploader_id': 'spbelect',
  753. 'uploader': 'Наблюдатели Петербурга',
  754. },
  755. 'params': {
  756. 'skip_download': 'requires avconv',
  757. },
  758. 'skip': 'This live event has ended.',
  759. },
  760. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  761. {
  762. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  763. 'info_dict': {
  764. 'id': 'FIl7x6_3R5Y',
  765. 'ext': 'webm',
  766. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  767. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  768. 'duration': 220,
  769. 'upload_date': '20150625',
  770. 'uploader_id': 'dorappi2000',
  771. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  772. 'uploader': 'dorappi2000',
  773. 'formats': 'mincount:31',
  774. },
  775. 'skip': 'not actual anymore',
  776. },
  777. # DASH manifest with segment_list
  778. {
  779. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  780. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  781. 'info_dict': {
  782. 'id': 'CsmdDsKjzN8',
  783. 'ext': 'mp4',
  784. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  785. 'uploader': 'Airtek',
  786. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  787. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  788. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  789. },
  790. 'params': {
  791. 'youtube_include_dash_manifest': True,
  792. 'format': '135', # bestvideo
  793. },
  794. 'skip': 'This live event has ended.',
  795. },
  796. {
  797. # Multifeed videos (multiple cameras), URL is for Main Camera
  798. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  799. 'info_dict': {
  800. 'id': 'jqWvoWXjCVs',
  801. 'title': 'teamPGP: Rocket League Noob Stream',
  802. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  803. },
  804. 'playlist': [{
  805. 'info_dict': {
  806. 'id': 'jqWvoWXjCVs',
  807. 'ext': 'mp4',
  808. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  809. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  810. 'duration': 7335,
  811. 'upload_date': '20150721',
  812. 'uploader': 'Beer Games Beer',
  813. 'uploader_id': 'beergamesbeer',
  814. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  815. 'license': 'Standard YouTube License',
  816. },
  817. }, {
  818. 'info_dict': {
  819. 'id': '6h8e8xoXJzg',
  820. 'ext': 'mp4',
  821. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  822. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  823. 'duration': 7337,
  824. 'upload_date': '20150721',
  825. 'uploader': 'Beer Games Beer',
  826. 'uploader_id': 'beergamesbeer',
  827. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  828. 'license': 'Standard YouTube License',
  829. },
  830. }, {
  831. 'info_dict': {
  832. 'id': 'PUOgX5z9xZw',
  833. 'ext': 'mp4',
  834. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  835. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  836. 'duration': 7337,
  837. 'upload_date': '20150721',
  838. 'uploader': 'Beer Games Beer',
  839. 'uploader_id': 'beergamesbeer',
  840. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  841. 'license': 'Standard YouTube License',
  842. },
  843. }, {
  844. 'info_dict': {
  845. 'id': 'teuwxikvS5k',
  846. 'ext': 'mp4',
  847. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  848. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  849. 'duration': 7334,
  850. 'upload_date': '20150721',
  851. 'uploader': 'Beer Games Beer',
  852. 'uploader_id': 'beergamesbeer',
  853. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  854. 'license': 'Standard YouTube License',
  855. },
  856. }],
  857. 'params': {
  858. 'skip_download': True,
  859. },
  860. 'skip': 'This video is not available.',
  861. },
  862. {
  863. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  864. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  865. 'info_dict': {
  866. 'id': 'gVfLd0zydlo',
  867. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  868. },
  869. 'playlist_count': 2,
  870. 'skip': 'Not multifeed anymore',
  871. },
  872. {
  873. 'url': 'https://vid.plus/FlRa-iH7PGw',
  874. 'only_matching': True,
  875. },
  876. {
  877. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  878. 'only_matching': True,
  879. },
  880. {
  881. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  882. # Also tests cut-off URL expansion in video description (see
  883. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  884. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  885. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  886. 'info_dict': {
  887. 'id': 'lsguqyKfVQg',
  888. 'ext': 'mp4',
  889. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  890. 'alt_title': 'Dark Walk - Position Music',
  891. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  892. 'duration': 133,
  893. 'upload_date': '20151119',
  894. 'uploader_id': 'IronSoulElf',
  895. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
  896. 'uploader': 'IronSoulElf',
  897. 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  898. 'track': 'Dark Walk - Position Music',
  899. 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  900. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  901. },
  902. 'params': {
  903. 'skip_download': True,
  904. },
  905. },
  906. {
  907. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  908. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  909. 'only_matching': True,
  910. },
  911. {
  912. # Video with yt:stretch=17:0
  913. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  914. 'info_dict': {
  915. 'id': 'Q39EVAstoRM',
  916. 'ext': 'mp4',
  917. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  918. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  919. 'upload_date': '20151107',
  920. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  921. 'uploader': 'CH GAMER DROID',
  922. },
  923. 'params': {
  924. 'skip_download': True,
  925. },
  926. 'skip': 'This video does not exist.',
  927. },
  928. {
  929. # Video licensed under Creative Commons
  930. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  931. 'info_dict': {
  932. 'id': 'M4gD1WSo5mA',
  933. 'ext': 'mp4',
  934. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  935. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  936. 'duration': 721,
  937. 'upload_date': '20150127',
  938. 'uploader_id': 'BerkmanCenter',
  939. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
  940. 'uploader': 'The Berkman Klein Center for Internet & Society',
  941. 'license': 'Creative Commons Attribution license (reuse allowed)',
  942. },
  943. 'params': {
  944. 'skip_download': True,
  945. },
  946. },
  947. {
  948. # Channel-like uploader_url
  949. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  950. 'info_dict': {
  951. 'id': 'eQcmzGIKrzg',
  952. 'ext': 'mp4',
  953. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  954. 'description': 'md5:dda0d780d5a6e120758d1711d062a867',
  955. 'duration': 4060,
  956. 'upload_date': '20151119',
  957. 'uploader': 'Bernie Sanders',
  958. 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
  959. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
  960. 'license': 'Creative Commons Attribution license (reuse allowed)',
  961. },
  962. 'params': {
  963. 'skip_download': True,
  964. },
  965. },
  966. {
  967. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  968. 'only_matching': True,
  969. },
  970. {
  971. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  972. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  973. 'only_matching': True,
  974. },
  975. {
  976. # Rental video preview
  977. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  978. 'info_dict': {
  979. 'id': 'uGpuVWrhIzE',
  980. 'ext': 'mp4',
  981. 'title': 'Piku - Trailer',
  982. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  983. 'upload_date': '20150811',
  984. 'uploader': 'FlixMatrix',
  985. 'uploader_id': 'FlixMatrixKaravan',
  986. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
  987. 'license': 'Standard YouTube License',
  988. },
  989. 'params': {
  990. 'skip_download': True,
  991. },
  992. 'skip': 'This video is not available.',
  993. },
  994. {
  995. # YouTube Red video with episode data
  996. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  997. 'info_dict': {
  998. 'id': 'iqKdEhx-dD4',
  999. 'ext': 'mp4',
  1000. 'title': 'Isolation - Mind Field (Ep 1)',
  1001. 'description': 'md5:46a29be4ceffa65b92d277b93f463c0f',
  1002. 'duration': 2085,
  1003. 'upload_date': '20170118',
  1004. 'uploader': 'Vsauce',
  1005. 'uploader_id': 'Vsauce',
  1006. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
  1007. 'series': 'Mind Field',
  1008. 'season_number': 1,
  1009. 'episode_number': 1,
  1010. },
  1011. 'params': {
  1012. 'skip_download': True,
  1013. },
  1014. 'expected_warnings': [
  1015. 'Skipping DASH manifest',
  1016. ],
  1017. },
  1018. {
  1019. # The following content has been identified by the YouTube community
  1020. # as inappropriate or offensive to some audiences.
  1021. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  1022. 'info_dict': {
  1023. 'id': '6SJNVb0GnPI',
  1024. 'ext': 'mp4',
  1025. 'title': 'Race Differences in Intelligence',
  1026. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  1027. 'duration': 965,
  1028. 'upload_date': '20140124',
  1029. 'uploader': 'New Century Foundation',
  1030. 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
  1031. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
  1032. },
  1033. 'params': {
  1034. 'skip_download': True,
  1035. },
  1036. },
  1037. {
  1038. # itag 212
  1039. 'url': '1t24XAntNCY',
  1040. 'only_matching': True,
  1041. },
  1042. {
  1043. # geo restricted to JP
  1044. 'url': 'sJL6WA-aGkQ',
  1045. 'only_matching': True,
  1046. },
  1047. {
  1048. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  1049. 'only_matching': True,
  1050. },
  1051. {
  1052. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  1053. 'only_matching': True,
  1054. },
  1055. {
  1056. # DRM protected
  1057. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  1058. 'only_matching': True,
  1059. },
  1060. {
  1061. # Video with unsupported adaptive stream type formats
  1062. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  1063. 'info_dict': {
  1064. 'id': 'Z4Vy8R84T1U',
  1065. 'ext': 'mp4',
  1066. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  1067. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  1068. 'duration': 433,
  1069. 'upload_date': '20130923',
  1070. 'uploader': 'Amelia Putri Harwita',
  1071. 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
  1072. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
  1073. 'formats': 'maxcount:10',
  1074. },
  1075. 'params': {
  1076. 'skip_download': True,
  1077. 'youtube_include_dash_manifest': False,
  1078. },
  1079. 'skip': 'not actual anymore',
  1080. },
  1081. {
  1082. # Youtube Music Auto-generated description
  1083. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  1084. 'info_dict': {
  1085. 'id': 'MgNrAu2pzNs',
  1086. 'ext': 'mp4',
  1087. 'title': 'Voyeur Girl',
  1088. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  1089. 'upload_date': '20190312',
  1090. 'uploader': 'Stephen - Topic',
  1091. 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
  1092. 'artist': 'Stephen',
  1093. 'track': 'Voyeur Girl',
  1094. 'album': 'it\'s too much love to know my dear',
  1095. 'release_date': '20190313',
  1096. 'release_year': 2019,
  1097. },
  1098. 'params': {
  1099. 'skip_download': True,
  1100. },
  1101. },
  1102. {
  1103. # Youtube Music Auto-generated description
  1104. # Retrieve 'artist' field from 'Artist:' in video description
  1105. # when it is present on youtube music video
  1106. 'url': 'https://www.youtube.com/watch?v=k0jLE7tTwjY',
  1107. 'info_dict': {
  1108. 'id': 'k0jLE7tTwjY',
  1109. 'ext': 'mp4',
  1110. 'title': 'Latch Feat. Sam Smith',
  1111. 'description': 'md5:3cb1e8101a7c85fcba9b4fb41b951335',
  1112. 'upload_date': '20150110',
  1113. 'uploader': 'Various Artists - Topic',
  1114. 'uploader_id': 'UCNkEcmYdjrH4RqtNgh7BZ9w',
  1115. 'artist': 'Disclosure',
  1116. 'track': 'Latch Feat. Sam Smith',
  1117. 'album': 'Latch Featuring Sam Smith',
  1118. 'release_date': '20121008',
  1119. 'release_year': 2012,
  1120. },
  1121. 'params': {
  1122. 'skip_download': True,
  1123. },
  1124. },
  1125. {
  1126. # Youtube Music Auto-generated description
  1127. # handle multiple artists on youtube music video
  1128. 'url': 'https://www.youtube.com/watch?v=74qn0eJSjpA',
  1129. 'info_dict': {
  1130. 'id': '74qn0eJSjpA',
  1131. 'ext': 'mp4',
  1132. 'title': 'Eastside',
  1133. 'description': 'md5:290516bb73dcbfab0dcc4efe6c3de5f2',
  1134. 'upload_date': '20180710',
  1135. 'uploader': 'Benny Blanco - Topic',
  1136. 'uploader_id': 'UCzqz_ksRu_WkIzmivMdIS7A',
  1137. 'artist': 'benny blanco, Halsey, Khalid',
  1138. 'track': 'Eastside',
  1139. 'album': 'Eastside',
  1140. 'release_date': '20180713',
  1141. 'release_year': 2018,
  1142. },
  1143. 'params': {
  1144. 'skip_download': True,
  1145. },
  1146. },
  1147. {
  1148. # Youtube Music Auto-generated description
  1149. # handle youtube music video with release_year and no release_date
  1150. 'url': 'https://www.youtube.com/watch?v=-hcAI0g-f5M',
  1151. 'info_dict': {
  1152. 'id': '-hcAI0g-f5M',
  1153. 'ext': 'mp4',
  1154. 'title': 'Put It On Me',
  1155. 'description': 'md5:f6422397c07c4c907c6638e1fee380a5',
  1156. 'upload_date': '20180426',
  1157. 'uploader': 'Matt Maeson - Topic',
  1158. 'uploader_id': 'UCnEkIGqtGcQMLk73Kp-Q5LQ',
  1159. 'artist': 'Matt Maeson',
  1160. 'track': 'Put It On Me',
  1161. 'album': 'The Hearse',
  1162. 'release_date': None,
  1163. 'release_year': 2018,
  1164. },
  1165. 'params': {
  1166. 'skip_download': True,
  1167. },
  1168. },
  1169. {
  1170. 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
  1171. 'only_matching': True,
  1172. },
  1173. {
  1174. # invalid -> valid video id redirection
  1175. 'url': 'DJztXj2GPfl',
  1176. 'info_dict': {
  1177. 'id': 'DJztXj2GPfk',
  1178. 'ext': 'mp4',
  1179. 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
  1180. 'description': 'md5:bf577a41da97918e94fa9798d9228825',
  1181. 'upload_date': '20090125',
  1182. 'uploader': 'Prochorowka',
  1183. 'uploader_id': 'Prochorowka',
  1184. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
  1185. 'artist': 'Panjabi MC',
  1186. 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
  1187. 'album': 'Beware of the Boys (Mundian To Bach Ke)',
  1188. },
  1189. 'params': {
  1190. 'skip_download': True,
  1191. },
  1192. }
  1193. ]
  1194. def __init__(self, *args, **kwargs):
  1195. super(YoutubeIE, self).__init__(*args, **kwargs)
  1196. self._player_cache = {}
  1197. def report_video_info_webpage_download(self, video_id):
  1198. """Report attempt to download video info webpage."""
  1199. self.to_screen('%s: Downloading video info webpage' % video_id)
  1200. def report_information_extraction(self, video_id):
  1201. """Report attempt to extract video information."""
  1202. self.to_screen('%s: Extracting video information' % video_id)
  1203. def report_unavailable_format(self, video_id, format):
  1204. """Report extracted video URL."""
  1205. self.to_screen('%s: Format %s not available' % (video_id, format))
  1206. def report_rtmp_download(self):
  1207. """Indicate the download will use the RTMP protocol."""
  1208. self.to_screen('RTMP download detected')
  1209. def _signature_cache_id(self, example_sig):
  1210. """ Return a string representation of a signature """
  1211. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  1212. @classmethod
  1213. def _extract_player_info(cls, player_url):
  1214. for player_re in cls._PLAYER_INFO_RE:
  1215. id_m = re.search(player_re, player_url)
  1216. if id_m:
  1217. break
  1218. else:
  1219. raise ExtractorError('Cannot identify player %r' % player_url)
  1220. return id_m.group('ext'), id_m.group('id')
  1221. def _extract_signature_function(self, video_id, player_url, example_sig):
  1222. player_type, player_id = self._extract_player_info(player_url)
  1223. # Read from filesystem cache
  1224. func_id = '%s_%s_%s' % (
  1225. player_type, player_id, self._signature_cache_id(example_sig))
  1226. assert os.path.basename(func_id) == func_id
  1227. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  1228. if cache_spec is not None:
  1229. return lambda s: ''.join(s[i] for i in cache_spec)
  1230. download_note = (
  1231. 'Downloading player %s' % player_url
  1232. if self._downloader.params.get('verbose') else
  1233. 'Downloading %s player %s' % (player_type, player_id)
  1234. )
  1235. if player_type == 'js':
  1236. code = self._download_webpage(
  1237. player_url, video_id,
  1238. note=download_note,
  1239. errnote='Download of %s failed' % player_url)
  1240. res = self._parse_sig_js(code)
  1241. elif player_type == 'swf':
  1242. urlh = self._request_webpage(
  1243. player_url, video_id,
  1244. note=download_note,
  1245. errnote='Download of %s failed' % player_url)
  1246. code = urlh.read()
  1247. res = self._parse_sig_swf(code)
  1248. else:
  1249. assert False, 'Invalid player type %r' % player_type
  1250. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1251. cache_res = res(test_string)
  1252. cache_spec = [ord(c) for c in cache_res]
  1253. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  1254. return res
  1255. def _print_sig_code(self, func, example_sig):
  1256. def gen_sig_code(idxs):
  1257. def _genslice(start, end, step):
  1258. starts = '' if start == 0 else str(start)
  1259. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  1260. steps = '' if step == 1 else (':%d' % step)
  1261. return 's[%s%s%s]' % (starts, ends, steps)
  1262. step = None
  1263. # Quelch pyflakes warnings - start will be set when step is set
  1264. start = '(Never used)'
  1265. for i, prev in zip(idxs[1:], idxs[:-1]):
  1266. if step is not None:
  1267. if i - prev == step:
  1268. continue
  1269. yield _genslice(start, prev, step)
  1270. step = None
  1271. continue
  1272. if i - prev in [-1, 1]:
  1273. step = i - prev
  1274. start = prev
  1275. continue
  1276. else:
  1277. yield 's[%d]' % prev
  1278. if step is None:
  1279. yield 's[%d]' % i
  1280. else:
  1281. yield _genslice(start, i, step)
  1282. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1283. cache_res = func(test_string)
  1284. cache_spec = [ord(c) for c in cache_res]
  1285. expr_code = ' + '.join(gen_sig_code(cache_spec))
  1286. signature_id_tuple = '(%s)' % (
  1287. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  1288. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  1289. ' return %s\n') % (signature_id_tuple, expr_code)
  1290. self.to_screen('Extracted signature function:\n' + code)
  1291. def _parse_sig_js(self, jscode):
  1292. funcname = self._search_regex(
  1293. (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1294. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1295. r'\b(?P<sig>[a-zA-Z0-9$]{2})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1296. r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1297. # Obsolete patterns
  1298. r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1299. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1300. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1301. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1302. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1303. r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1304. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1305. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
  1306. jscode, 'Initial JS player signature function name', group='sig')
  1307. jsi = JSInterpreter(jscode)
  1308. initial_function = jsi.extract_function(funcname)
  1309. return lambda s: initial_function([s])
  1310. def _parse_sig_swf(self, file_contents):
  1311. swfi = SWFInterpreter(file_contents)
  1312. TARGET_CLASSNAME = 'SignatureDecipher'
  1313. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  1314. initial_function = swfi.extract_function(searched_class, 'decipher')
  1315. return lambda s: initial_function([s])
  1316. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  1317. """Turn the encrypted s field into a working signature"""
  1318. if player_url is None:
  1319. raise ExtractorError('Cannot decrypt signature without player_url')
  1320. if player_url.startswith('//'):
  1321. player_url = 'https:' + player_url
  1322. elif not re.match(r'https?://', player_url):
  1323. player_url = compat_urlparse.urljoin(
  1324. 'https://www.youtube.com', player_url)
  1325. try:
  1326. player_id = (player_url, self._signature_cache_id(s))
  1327. if player_id not in self._player_cache:
  1328. func = self._extract_signature_function(
  1329. video_id, player_url, s
  1330. )
  1331. self._player_cache[player_id] = func
  1332. func = self._player_cache[player_id]
  1333. if self._downloader.params.get('youtube_print_sig_code'):
  1334. self._print_sig_code(func, s)
  1335. return func(s)
  1336. except Exception as e:
  1337. tb = traceback.format_exc()
  1338. raise ExtractorError(
  1339. 'Signature extraction failed: ' + tb, cause=e)
  1340. def _get_subtitles(self, video_id, webpage):
  1341. try:
  1342. subs_doc = self._download_xml(
  1343. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1344. video_id, note=False)
  1345. except ExtractorError as err:
  1346. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  1347. return {}
  1348. sub_lang_list = {}
  1349. for track in subs_doc.findall('track'):
  1350. lang = track.attrib['lang_code']
  1351. if lang in sub_lang_list:
  1352. continue
  1353. sub_formats = []
  1354. for ext in self._SUBTITLE_FORMATS:
  1355. params = compat_urllib_parse_urlencode({
  1356. 'lang': lang,
  1357. 'v': video_id,
  1358. 'fmt': ext,
  1359. 'name': track.attrib['name'].encode('utf-8'),
  1360. })
  1361. sub_formats.append({
  1362. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  1363. 'ext': ext,
  1364. })
  1365. sub_lang_list[lang] = sub_formats
  1366. if not sub_lang_list:
  1367. self._downloader.report_warning('video doesn\'t have subtitles')
  1368. return {}
  1369. return sub_lang_list
  1370. def _get_ytplayer_config(self, video_id, webpage):
  1371. patterns = (
  1372. # User data may contain arbitrary character sequences that may affect
  1373. # JSON extraction with regex, e.g. when '};' is contained the second
  1374. # regex won't capture the whole JSON. Yet working around by trying more
  1375. # concrete regex first keeping in mind proper quoted string handling
  1376. # to be implemented in future that will replace this workaround (see
  1377. # https://github.com/ytdl-org/youtube-dl/issues/7468,
  1378. # https://github.com/ytdl-org/youtube-dl/pull/7599)
  1379. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  1380. r';ytplayer\.config\s*=\s*({.+?});',
  1381. )
  1382. config = self._search_regex(
  1383. patterns, webpage, 'ytplayer.config', default=None)
  1384. if config:
  1385. return self._parse_json(
  1386. uppercase_escape(config), video_id, fatal=False)
  1387. def _get_automatic_captions(self, video_id, webpage):
  1388. """We need the webpage for getting the captions url, pass it as an
  1389. argument to speed up the process."""
  1390. self.to_screen('%s: Looking for automatic captions' % video_id)
  1391. player_config = self._get_ytplayer_config(video_id, webpage)
  1392. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  1393. if not player_config:
  1394. self._downloader.report_warning(err_msg)
  1395. return {}
  1396. try:
  1397. args = player_config['args']
  1398. caption_url = args.get('ttsurl')
  1399. if caption_url:
  1400. timestamp = args['timestamp']
  1401. # We get the available subtitles
  1402. list_params = compat_urllib_parse_urlencode({
  1403. 'type': 'list',
  1404. 'tlangs': 1,
  1405. 'asrs': 1,
  1406. })
  1407. list_url = caption_url + '&' + list_params
  1408. caption_list = self._download_xml(list_url, video_id)
  1409. original_lang_node = caption_list.find('track')
  1410. if original_lang_node is None:
  1411. self._downloader.report_warning('Video doesn\'t have automatic captions')
  1412. return {}
  1413. original_lang = original_lang_node.attrib['lang_code']
  1414. caption_kind = original_lang_node.attrib.get('kind', '')
  1415. sub_lang_list = {}
  1416. for lang_node in caption_list.findall('target'):
  1417. sub_lang = lang_node.attrib['lang_code']
  1418. sub_formats = []
  1419. for ext in self._SUBTITLE_FORMATS:
  1420. params = compat_urllib_parse_urlencode({
  1421. 'lang': original_lang,
  1422. 'tlang': sub_lang,
  1423. 'fmt': ext,
  1424. 'ts': timestamp,
  1425. 'kind': caption_kind,
  1426. })
  1427. sub_formats.append({
  1428. 'url': caption_url + '&' + params,
  1429. 'ext': ext,
  1430. })
  1431. sub_lang_list[sub_lang] = sub_formats
  1432. return sub_lang_list
  1433. def make_captions(sub_url, sub_langs):
  1434. parsed_sub_url = compat_urllib_parse_urlparse(sub_url)
  1435. caption_qs = compat_parse_qs(parsed_sub_url.query)
  1436. captions = {}
  1437. for sub_lang in sub_langs:
  1438. sub_formats = []
  1439. for ext in self._SUBTITLE_FORMATS:
  1440. caption_qs.update({
  1441. 'tlang': [sub_lang],
  1442. 'fmt': [ext],
  1443. })
  1444. sub_url = compat_urlparse.urlunparse(parsed_sub_url._replace(
  1445. query=compat_urllib_parse_urlencode(caption_qs, True)))
  1446. sub_formats.append({
  1447. 'url': sub_url,
  1448. 'ext': ext,
  1449. })
  1450. captions[sub_lang] = sub_formats
  1451. return captions
  1452. # New captions format as of 22.06.2017
  1453. player_response = args.get('player_response')
  1454. if player_response and isinstance(player_response, compat_str):
  1455. player_response = self._parse_json(
  1456. player_response, video_id, fatal=False)
  1457. if player_response:
  1458. renderer = player_response['captions']['playerCaptionsTracklistRenderer']
  1459. base_url = renderer['captionTracks'][0]['baseUrl']
  1460. sub_lang_list = []
  1461. for lang in renderer['translationLanguages']:
  1462. lang_code = lang.get('languageCode')
  1463. if lang_code:
  1464. sub_lang_list.append(lang_code)
  1465. return make_captions(base_url, sub_lang_list)
  1466. # Some videos don't provide ttsurl but rather caption_tracks and
  1467. # caption_translation_languages (e.g. 20LmZk1hakA)
  1468. # Does not used anymore as of 22.06.2017
  1469. caption_tracks = args['caption_tracks']
  1470. caption_translation_languages = args['caption_translation_languages']
  1471. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1472. sub_lang_list = []
  1473. for lang in caption_translation_languages.split(','):
  1474. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1475. sub_lang = lang_qs.get('lc', [None])[0]
  1476. if sub_lang:
  1477. sub_lang_list.append(sub_lang)
  1478. return make_captions(caption_url, sub_lang_list)
  1479. # An extractor error can be raise by the download process if there are
  1480. # no automatic captions but there are subtitles
  1481. except (KeyError, IndexError, ExtractorError):
  1482. self._downloader.report_warning(err_msg)
  1483. return {}
  1484. def _mark_watched(self, video_id, video_info, player_response):
  1485. playback_url = url_or_none(try_get(
  1486. player_response,
  1487. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']) or try_get(
  1488. video_info, lambda x: x['videostats_playback_base_url'][0]))
  1489. if not playback_url:
  1490. return
  1491. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1492. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1493. # cpn generation algorithm is reverse engineered from base.js.
  1494. # In fact it works even with dummy cpn.
  1495. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1496. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1497. qs.update({
  1498. 'ver': ['2'],
  1499. 'cpn': [cpn],
  1500. })
  1501. playback_url = compat_urlparse.urlunparse(
  1502. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1503. self._download_webpage(
  1504. playback_url, video_id, 'Marking watched',
  1505. 'Unable to mark watched', fatal=False)
  1506. @staticmethod
  1507. def _extract_urls(webpage):
  1508. # Embedded YouTube player
  1509. entries = [
  1510. unescapeHTML(mobj.group('url'))
  1511. for mobj in re.finditer(r'''(?x)
  1512. (?:
  1513. <iframe[^>]+?src=|
  1514. data-video-url=|
  1515. <embed[^>]+?src=|
  1516. embedSWF\(?:\s*|
  1517. <object[^>]+data=|
  1518. new\s+SWFObject\(
  1519. )
  1520. (["\'])
  1521. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1522. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1523. \1''', webpage)]
  1524. # lazyYT YouTube embed
  1525. entries.extend(list(map(
  1526. unescapeHTML,
  1527. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  1528. # Wordpress "YouTube Video Importer" plugin
  1529. matches = re.findall(r'''(?x)<div[^>]+
  1530. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  1531. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  1532. entries.extend(m[-1] for m in matches)
  1533. return entries
  1534. @staticmethod
  1535. def _extract_url(webpage):
  1536. urls = YoutubeIE._extract_urls(webpage)
  1537. return urls[0] if urls else None
  1538. @classmethod
  1539. def extract_id(cls, url):
  1540. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1541. if mobj is None:
  1542. raise ExtractorError('Invalid URL: %s' % url)
  1543. video_id = mobj.group(2)
  1544. return video_id
  1545. @staticmethod
  1546. def _extract_chapters(description, duration):
  1547. if not description:
  1548. return None
  1549. chapter_lines = re.findall(
  1550. r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
  1551. description)
  1552. if not chapter_lines:
  1553. return None
  1554. chapters = []
  1555. for next_num, (chapter_line, time_point) in enumerate(
  1556. chapter_lines, start=1):
  1557. start_time = parse_duration(time_point)
  1558. if start_time is None:
  1559. continue
  1560. if start_time > duration:
  1561. break
  1562. end_time = (duration if next_num == len(chapter_lines)
  1563. else parse_duration(chapter_lines[next_num][1]))
  1564. if end_time is None:
  1565. continue
  1566. if end_time > duration:
  1567. end_time = duration
  1568. if start_time > end_time:
  1569. break
  1570. chapter_title = re.sub(
  1571. r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
  1572. chapter_title = re.sub(r'\s+', ' ', chapter_title)
  1573. chapters.append({
  1574. 'start_time': start_time,
  1575. 'end_time': end_time,
  1576. 'title': chapter_title,
  1577. })
  1578. return chapters
  1579. def _real_extract(self, url):
  1580. url, smuggled_data = unsmuggle_url(url, {})
  1581. proto = (
  1582. 'http' if self._downloader.params.get('prefer_insecure', False)
  1583. else 'https')
  1584. start_time = None
  1585. end_time = None
  1586. parsed_url = compat_urllib_parse_urlparse(url)
  1587. for component in [parsed_url.fragment, parsed_url.query]:
  1588. query = compat_parse_qs(component)
  1589. if start_time is None and 't' in query:
  1590. start_time = parse_duration(query['t'][0])
  1591. if start_time is None and 'start' in query:
  1592. start_time = parse_duration(query['start'][0])
  1593. if end_time is None and 'end' in query:
  1594. end_time = parse_duration(query['end'][0])
  1595. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1596. mobj = re.search(self._NEXT_URL_RE, url)
  1597. if mobj:
  1598. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1599. video_id = self.extract_id(url)
  1600. # Get video webpage
  1601. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1602. video_webpage, urlh = self._download_webpage_handle(url, video_id)
  1603. qs = compat_parse_qs(compat_urllib_parse_urlparse(urlh.geturl()).query)
  1604. video_id = qs.get('v', [None])[0] or video_id
  1605. # Attempt to extract SWF player URL
  1606. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1607. if mobj is not None:
  1608. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1609. else:
  1610. player_url = None
  1611. dash_mpds = []
  1612. def add_dash_mpd(video_info):
  1613. dash_mpd = video_info.get('dashmpd')
  1614. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1615. dash_mpds.append(dash_mpd[0])
  1616. def add_dash_mpd_pr(pl_response):
  1617. dash_mpd = url_or_none(try_get(
  1618. pl_response, lambda x: x['streamingData']['dashManifestUrl'],
  1619. compat_str))
  1620. if dash_mpd and dash_mpd not in dash_mpds:
  1621. dash_mpds.append(dash_mpd)
  1622. is_live = None
  1623. view_count = None
  1624. def extract_view_count(v_info):
  1625. return int_or_none(try_get(v_info, lambda x: x['view_count'][0]))
  1626. def extract_player_response(player_response, video_id):
  1627. pl_response = str_or_none(player_response)
  1628. if not pl_response:
  1629. return
  1630. pl_response = self._parse_json(pl_response, video_id, fatal=False)
  1631. if isinstance(pl_response, dict):
  1632. add_dash_mpd_pr(pl_response)
  1633. return pl_response
  1634. player_response = {}
  1635. # Get video info
  1636. video_info = {}
  1637. embed_webpage = None
  1638. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1639. age_gate = True
  1640. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1641. # this can be viewed without login into Youtube
  1642. url = proto + '://www.youtube.com/embed/%s' % video_id
  1643. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1644. data = compat_urllib_parse_urlencode({
  1645. 'video_id': video_id,
  1646. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1647. 'sts': self._search_regex(
  1648. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1649. })
  1650. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1651. try:
  1652. video_info_webpage = self._download_webpage(
  1653. video_info_url, video_id,
  1654. note='Refetching age-gated info webpage',
  1655. errnote='unable to download video info webpage')
  1656. except ExtractorError:
  1657. video_info_webpage = None
  1658. if video_info_webpage:
  1659. video_info = compat_parse_qs(video_info_webpage)
  1660. pl_response = video_info.get('player_response', [None])[0]
  1661. player_response = extract_player_response(pl_response, video_id)
  1662. add_dash_mpd(video_info)
  1663. view_count = extract_view_count(video_info)
  1664. else:
  1665. age_gate = False
  1666. # Try looking directly into the video webpage
  1667. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1668. if ytplayer_config:
  1669. args = ytplayer_config['args']
  1670. if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
  1671. # Convert to the same format returned by compat_parse_qs
  1672. video_info = dict((k, [v]) for k, v in args.items())
  1673. add_dash_mpd(video_info)
  1674. # Rental video is not rented but preview is available (e.g.
  1675. # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
  1676. # https://github.com/ytdl-org/youtube-dl/issues/10532)
  1677. if not video_info and args.get('ypc_vid'):
  1678. return self.url_result(
  1679. args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
  1680. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1681. is_live = True
  1682. if not player_response:
  1683. player_response = extract_player_response(args.get('player_response'), video_id)
  1684. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1685. add_dash_mpd_pr(player_response)
  1686. def extract_unavailable_message():
  1687. messages = []
  1688. for tag, kind in (('h1', 'message'), ('div', 'submessage')):
  1689. msg = self._html_search_regex(
  1690. r'(?s)<{tag}[^>]+id=["\']unavailable-{kind}["\'][^>]*>(.+?)</{tag}>'.format(tag=tag, kind=kind),
  1691. video_webpage, 'unavailable %s' % kind, default=None)
  1692. if msg:
  1693. messages.append(msg)
  1694. if messages:
  1695. return '\n'.join(messages)
  1696. if not video_info and not player_response:
  1697. unavailable_message = extract_unavailable_message()
  1698. if not unavailable_message:
  1699. unavailable_message = 'Unable to extract video data'
  1700. raise ExtractorError(
  1701. 'YouTube said: %s' % unavailable_message, expected=True, video_id=video_id)
  1702. if not isinstance(video_info, dict):
  1703. video_info = {}
  1704. video_details = try_get(
  1705. player_response, lambda x: x['videoDetails'], dict) or {}
  1706. video_title = video_info.get('title', [None])[0] or video_details.get('title')
  1707. if not video_title:
  1708. self._downloader.report_warning('Unable to extract video title')
  1709. video_title = '_'
  1710. description_original = video_description = get_element_by_id("eow-description", video_webpage)
  1711. if video_description:
  1712. def replace_url(m):
  1713. redir_url = compat_urlparse.urljoin(url, m.group(1))
  1714. parsed_redir_url = compat_urllib_parse_urlparse(redir_url)
  1715. if re.search(r'^(?:www\.)?(?:youtube(?:-nocookie)?\.com|youtu\.be)$', parsed_redir_url.netloc) and parsed_redir_url.path == '/redirect':
  1716. qs = compat_parse_qs(parsed_redir_url.query)
  1717. q = qs.get('q')
  1718. if q and q[0]:
  1719. return q[0]
  1720. return redir_url
  1721. description_original = video_description = re.sub(r'''(?x)
  1722. <a\s+
  1723. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1724. (?:title|href)="([^"]+)"\s+
  1725. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1726. class="[^"]*"[^>]*>
  1727. [^<]+\.{3}\s*
  1728. </a>
  1729. ''', replace_url, video_description)
  1730. video_description = clean_html(video_description)
  1731. else:
  1732. video_description = self._html_search_meta('description', video_webpage) or video_details.get('shortDescription')
  1733. if not smuggled_data.get('force_singlefeed', False):
  1734. if not self._downloader.params.get('noplaylist'):
  1735. multifeed_metadata_list = try_get(
  1736. player_response,
  1737. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1738. compat_str) or try_get(
  1739. video_info, lambda x: x['multifeed_metadata_list'][0], compat_str)
  1740. if multifeed_metadata_list:
  1741. entries = []
  1742. feed_ids = []
  1743. for feed in multifeed_metadata_list.split(','):
  1744. # Unquote should take place before split on comma (,) since textual
  1745. # fields may contain comma as well (see
  1746. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1747. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1748. def feed_entry(name):
  1749. return try_get(feed_data, lambda x: x[name][0], compat_str)
  1750. feed_id = feed_entry('id')
  1751. if not feed_id:
  1752. continue
  1753. feed_title = feed_entry('title')
  1754. title = video_title
  1755. if feed_title:
  1756. title += ' (%s)' % feed_title
  1757. entries.append({
  1758. '_type': 'url_transparent',
  1759. 'ie_key': 'Youtube',
  1760. 'url': smuggle_url(
  1761. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1762. {'force_singlefeed': True}),
  1763. 'title': title,
  1764. })
  1765. feed_ids.append(feed_id)
  1766. self.to_screen(
  1767. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1768. % (', '.join(feed_ids), video_id))
  1769. return self.playlist_result(entries, video_id, video_title, video_description)
  1770. else:
  1771. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1772. if view_count is None:
  1773. view_count = extract_view_count(video_info)
  1774. if view_count is None and video_details:
  1775. view_count = int_or_none(video_details.get('viewCount'))
  1776. if is_live is None:
  1777. is_live = bool_or_none(video_details.get('isLive'))
  1778. # Check for "rental" videos
  1779. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1780. raise ExtractorError('"rental" videos not supported. See https://github.com/ytdl-org/youtube-dl/issues/359 for more information.', expected=True)
  1781. def _extract_filesize(media_url):
  1782. return int_or_none(self._search_regex(
  1783. r'\bclen[=/](\d+)', media_url, 'filesize', default=None))
  1784. streaming_formats = try_get(player_response, lambda x: x['streamingData']['formats'], list) or []
  1785. streaming_formats.extend(try_get(player_response, lambda x: x['streamingData']['adaptiveFormats'], list) or [])
  1786. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1787. self.report_rtmp_download()
  1788. formats = [{
  1789. 'format_id': '_rtmp',
  1790. 'protocol': 'rtmp',
  1791. 'url': video_info['conn'][0],
  1792. 'player_url': player_url,
  1793. }]
  1794. elif not is_live and (streaming_formats or len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1):
  1795. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1796. if 'rtmpe%3Dyes' in encoded_url_map:
  1797. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/ytdl-org/youtube-dl/issues/343 for more information.', expected=True)
  1798. formats = []
  1799. formats_spec = {}
  1800. fmt_list = video_info.get('fmt_list', [''])[0]
  1801. if fmt_list:
  1802. for fmt in fmt_list.split(','):
  1803. spec = fmt.split('/')
  1804. if len(spec) > 1:
  1805. width_height = spec[1].split('x')
  1806. if len(width_height) == 2:
  1807. formats_spec[spec[0]] = {
  1808. 'resolution': spec[1],
  1809. 'width': int_or_none(width_height[0]),
  1810. 'height': int_or_none(width_height[1]),
  1811. }
  1812. for fmt in streaming_formats:
  1813. itag = str_or_none(fmt.get('itag'))
  1814. if not itag:
  1815. continue
  1816. quality = fmt.get('quality')
  1817. quality_label = fmt.get('qualityLabel') or quality
  1818. formats_spec[itag] = {
  1819. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1820. 'filesize': int_or_none(fmt.get('contentLength')),
  1821. 'format_note': quality_label,
  1822. 'fps': int_or_none(fmt.get('fps')),
  1823. 'height': int_or_none(fmt.get('height')),
  1824. # bitrate for itag 43 is always 2147483647
  1825. 'tbr': float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000) if itag != '43' else None,
  1826. 'width': int_or_none(fmt.get('width')),
  1827. }
  1828. for fmt in streaming_formats:
  1829. if fmt.get('drmFamilies') or fmt.get('drm_families'):
  1830. continue
  1831. url = url_or_none(fmt.get('url'))
  1832. if not url:
  1833. cipher = fmt.get('cipher') or fmt.get('signatureCipher')
  1834. if not cipher:
  1835. continue
  1836. url_data = compat_parse_qs(cipher)
  1837. url = url_or_none(try_get(url_data, lambda x: x['url'][0], compat_str))
  1838. if not url:
  1839. continue
  1840. else:
  1841. cipher = None
  1842. url_data = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  1843. stream_type = int_or_none(try_get(url_data, lambda x: x['stream_type'][0]))
  1844. # Unsupported FORMAT_STREAM_TYPE_OTF
  1845. if stream_type == 3:
  1846. continue
  1847. format_id = fmt.get('itag') or url_data['itag'][0]
  1848. if not format_id:
  1849. continue
  1850. format_id = compat_str(format_id)
  1851. if cipher:
  1852. if 's' in url_data or self._downloader.params.get('youtube_include_dash_manifest', True):
  1853. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1854. jsplayer_url_json = self._search_regex(
  1855. ASSETS_RE,
  1856. embed_webpage if age_gate else video_webpage,
  1857. 'JS player URL (1)', default=None)
  1858. if not jsplayer_url_json and not age_gate:
  1859. # We need the embed website after all
  1860. if embed_webpage is None:
  1861. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1862. embed_webpage = self._download_webpage(
  1863. embed_url, video_id, 'Downloading embed webpage')
  1864. jsplayer_url_json = self._search_regex(
  1865. ASSETS_RE, embed_webpage, 'JS player URL')
  1866. player_url = json.loads(jsplayer_url_json)
  1867. if player_url is None:
  1868. player_url_json = self._search_regex(
  1869. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1870. video_webpage, 'age gate player URL')
  1871. player_url = json.loads(player_url_json)
  1872. if 'sig' in url_data:
  1873. url += '&signature=' + url_data['sig'][0]
  1874. elif 's' in url_data:
  1875. encrypted_sig = url_data['s'][0]
  1876. if self._downloader.params.get('verbose'):
  1877. if player_url is None:
  1878. player_desc = 'unknown'
  1879. else:
  1880. player_type, player_version = self._extract_player_info(player_url)
  1881. player_desc = '%s player %s' % ('flash' if player_type == 'swf' else 'html5', player_version)
  1882. parts_sizes = self._signature_cache_id(encrypted_sig)
  1883. self.to_screen('{%s} signature length %s, %s' %
  1884. (format_id, parts_sizes, player_desc))
  1885. signature = self._decrypt_signature(
  1886. encrypted_sig, video_id, player_url, age_gate)
  1887. sp = try_get(url_data, lambda x: x['sp'][0], compat_str) or 'signature'
  1888. url += '&%s=%s' % (sp, signature)
  1889. if 'ratebypass' not in url:
  1890. url += '&ratebypass=yes'
  1891. dct = {
  1892. 'format_id': format_id,
  1893. 'url': url,
  1894. 'player_url': player_url,
  1895. }
  1896. if format_id in self._formats:
  1897. dct.update(self._formats[format_id])
  1898. if format_id in formats_spec:
  1899. dct.update(formats_spec[format_id])
  1900. # Some itags are not included in DASH manifest thus corresponding formats will
  1901. # lack metadata (see https://github.com/ytdl-org/youtube-dl/pull/5993).
  1902. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1903. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1904. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1905. if width is None:
  1906. width = int_or_none(fmt.get('width'))
  1907. if height is None:
  1908. height = int_or_none(fmt.get('height'))
  1909. filesize = int_or_none(url_data.get(
  1910. 'clen', [None])[0]) or _extract_filesize(url)
  1911. quality = url_data.get('quality', [None])[0] or fmt.get('quality')
  1912. quality_label = url_data.get('quality_label', [None])[0] or fmt.get('qualityLabel')
  1913. tbr = (float_or_none(url_data.get('bitrate', [None])[0], 1000)
  1914. or float_or_none(fmt.get('bitrate'), 1000)) if format_id != '43' else None
  1915. fps = int_or_none(url_data.get('fps', [None])[0]) or int_or_none(fmt.get('fps'))
  1916. more_fields = {
  1917. 'filesize': filesize,
  1918. 'tbr': tbr,
  1919. 'width': width,
  1920. 'height': height,
  1921. 'fps': fps,
  1922. 'format_note': quality_label or quality,
  1923. }
  1924. for key, value in more_fields.items():
  1925. if value:
  1926. dct[key] = value
  1927. type_ = url_data.get('type', [None])[0] or fmt.get('mimeType')
  1928. if type_:
  1929. type_split = type_.split(';')
  1930. kind_ext = type_split[0].split('/')
  1931. if len(kind_ext) == 2:
  1932. kind, _ = kind_ext
  1933. dct['ext'] = mimetype2ext(type_split[0])
  1934. if kind in ('audio', 'video'):
  1935. codecs = None
  1936. for mobj in re.finditer(
  1937. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1938. if mobj.group('key') == 'codecs':
  1939. codecs = mobj.group('val')
  1940. break
  1941. if codecs:
  1942. dct.update(parse_codecs(codecs))
  1943. if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
  1944. dct['downloader_options'] = {
  1945. # Youtube throttles chunks >~10M
  1946. 'http_chunk_size': 10485760,
  1947. }
  1948. formats.append(dct)
  1949. else:
  1950. manifest_url = (
  1951. url_or_none(try_get(
  1952. player_response,
  1953. lambda x: x['streamingData']['hlsManifestUrl'],
  1954. compat_str))
  1955. or url_or_none(try_get(
  1956. video_info, lambda x: x['hlsvp'][0], compat_str)))
  1957. if manifest_url:
  1958. formats = []
  1959. m3u8_formats = self._extract_m3u8_formats(
  1960. manifest_url, video_id, 'mp4', fatal=False)
  1961. for a_format in m3u8_formats:
  1962. itag = self._search_regex(
  1963. r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
  1964. if itag:
  1965. a_format['format_id'] = itag
  1966. if itag in self._formats:
  1967. dct = self._formats[itag].copy()
  1968. dct.update(a_format)
  1969. a_format = dct
  1970. a_format['player_url'] = player_url
  1971. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1972. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1973. formats.append(a_format)
  1974. else:
  1975. error_message = extract_unavailable_message()
  1976. if not error_message:
  1977. error_message = clean_html(try_get(
  1978. player_response, lambda x: x['playabilityStatus']['reason'],
  1979. compat_str))
  1980. if not error_message:
  1981. error_message = clean_html(
  1982. try_get(video_info, lambda x: x['reason'][0], compat_str))
  1983. if error_message:
  1984. raise ExtractorError(error_message, expected=True)
  1985. raise ExtractorError('no conn, hlsvp, hlsManifestUrl or url_encoded_fmt_stream_map information found in video info')
  1986. # uploader
  1987. video_uploader = try_get(
  1988. video_info, lambda x: x['author'][0],
  1989. compat_str) or str_or_none(video_details.get('author'))
  1990. if video_uploader:
  1991. video_uploader = compat_urllib_parse_unquote_plus(video_uploader)
  1992. else:
  1993. self._downloader.report_warning('unable to extract uploader name')
  1994. # uploader_id
  1995. video_uploader_id = None
  1996. video_uploader_url = None
  1997. mobj = re.search(
  1998. r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  1999. video_webpage)
  2000. if mobj is not None:
  2001. video_uploader_id = mobj.group('uploader_id')
  2002. video_uploader_url = mobj.group('uploader_url')
  2003. else:
  2004. self._downloader.report_warning('unable to extract uploader nickname')
  2005. channel_id = (
  2006. str_or_none(video_details.get('channelId'))
  2007. or self._html_search_meta(
  2008. 'channelId', video_webpage, 'channel id', default=None)
  2009. or self._search_regex(
  2010. r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  2011. video_webpage, 'channel id', default=None, group='id'))
  2012. channel_url = 'http://www.youtube.com/channel/%s' % channel_id if channel_id else None
  2013. # thumbnail image
  2014. # We try first to get a high quality image:
  2015. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  2016. video_webpage, re.DOTALL)
  2017. if m_thumb is not None:
  2018. video_thumbnail = m_thumb.group(1)
  2019. elif 'thumbnail_url' not in video_info:
  2020. self._downloader.report_warning('unable to extract video thumbnail')
  2021. video_thumbnail = None
  2022. else: # don't panic if we can't find it
  2023. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  2024. # upload date
  2025. upload_date = self._html_search_meta(
  2026. 'datePublished', video_webpage, 'upload date', default=None)
  2027. if not upload_date:
  2028. upload_date = self._search_regex(
  2029. [r'(?s)id="eow-date.*?>(.*?)</span>',
  2030. r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'],
  2031. video_webpage, 'upload date', default=None)
  2032. upload_date = unified_strdate(upload_date)
  2033. video_license = self._html_search_regex(
  2034. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  2035. video_webpage, 'license', default=None)
  2036. m_music = re.search(
  2037. r'''(?x)
  2038. <h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*
  2039. <ul[^>]*>\s*
  2040. <li>(?P<title>.+?)
  2041. by (?P<creator>.+?)
  2042. (?:
  2043. \(.+?\)|
  2044. <a[^>]*
  2045. (?:
  2046. \bhref=["\']/red[^>]*>| # drop possible
  2047. >\s*Listen ad-free with YouTube Red # YouTube Red ad
  2048. )
  2049. .*?
  2050. )?</li
  2051. ''',
  2052. video_webpage)
  2053. if m_music:
  2054. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  2055. video_creator = clean_html(m_music.group('creator'))
  2056. else:
  2057. video_alt_title = video_creator = None
  2058. def extract_meta(field):
  2059. return self._html_search_regex(
  2060. r'<h4[^>]+class="title"[^>]*>\s*%s\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li>\s*' % field,
  2061. video_webpage, field, default=None)
  2062. track = extract_meta('Song')
  2063. artist = extract_meta('Artist')
  2064. album = extract_meta('Album')
  2065. # Youtube Music Auto-generated description
  2066. release_date = release_year = None
  2067. if video_description:
  2068. mobj = re.search(r'(?s)Provided to YouTube by [^\n]+\n+(?P<track>[^·]+)·(?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]+))?', video_description)
  2069. if mobj:
  2070. if not track:
  2071. track = mobj.group('track').strip()
  2072. if not artist:
  2073. artist = mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·'))
  2074. if not album:
  2075. album = mobj.group('album'.strip())
  2076. release_year = mobj.group('release_year')
  2077. release_date = mobj.group('release_date')
  2078. if release_date:
  2079. release_date = release_date.replace('-', '')
  2080. if not release_year:
  2081. release_year = int(release_date[:4])
  2082. if release_year:
  2083. release_year = int(release_year)
  2084. m_episode = re.search(
  2085. r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
  2086. video_webpage)
  2087. if m_episode:
  2088. series = unescapeHTML(m_episode.group('series'))
  2089. season_number = int(m_episode.group('season'))
  2090. episode_number = int(m_episode.group('episode'))
  2091. else:
  2092. series = season_number = episode_number = None
  2093. m_cat_container = self._search_regex(
  2094. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  2095. video_webpage, 'categories', default=None)
  2096. if m_cat_container:
  2097. category = self._html_search_regex(
  2098. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  2099. default=None)
  2100. video_categories = None if category is None else [category]
  2101. else:
  2102. video_categories = None
  2103. video_tags = [
  2104. unescapeHTML(m.group('content'))
  2105. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  2106. def _extract_count(count_name):
  2107. return str_to_int(self._search_regex(
  2108. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  2109. % re.escape(count_name),
  2110. video_webpage, count_name, default=None))
  2111. like_count = _extract_count('like')
  2112. dislike_count = _extract_count('dislike')
  2113. if view_count is None:
  2114. view_count = str_to_int(self._search_regex(
  2115. r'<[^>]+class=["\']watch-view-count[^>]+>\s*([\d,\s]+)', video_webpage,
  2116. 'view count', default=None))
  2117. average_rating = (
  2118. float_or_none(video_details.get('averageRating'))
  2119. or try_get(video_info, lambda x: float_or_none(x['avg_rating'][0])))
  2120. # subtitles
  2121. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  2122. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  2123. video_duration = try_get(
  2124. video_info, lambda x: int_or_none(x['length_seconds'][0]))
  2125. if not video_duration:
  2126. video_duration = int_or_none(video_details.get('lengthSeconds'))
  2127. if not video_duration:
  2128. video_duration = parse_duration(self._html_search_meta(
  2129. 'duration', video_webpage, 'video duration'))
  2130. # annotations
  2131. video_annotations = None
  2132. if self._downloader.params.get('writeannotations', False):
  2133. xsrf_token = self._search_regex(
  2134. r'([\'"])XSRF_TOKEN\1\s*:\s*([\'"])(?P<xsrf_token>[A-Za-z0-9+/=]+)\2',
  2135. video_webpage, 'xsrf token', group='xsrf_token', fatal=False)
  2136. invideo_url = try_get(
  2137. player_response, lambda x: x['annotations'][0]['playerAnnotationsUrlsRenderer']['invideoUrl'], compat_str)
  2138. if xsrf_token and invideo_url:
  2139. xsrf_field_name = self._search_regex(
  2140. r'([\'"])XSRF_FIELD_NAME\1\s*:\s*([\'"])(?P<xsrf_field_name>\w+)\2',
  2141. video_webpage, 'xsrf field name',
  2142. group='xsrf_field_name', default='session_token')
  2143. video_annotations = self._download_webpage(
  2144. self._proto_relative_url(invideo_url),
  2145. video_id, note='Downloading annotations',
  2146. errnote='Unable to download video annotations', fatal=False,
  2147. data=urlencode_postdata({xsrf_field_name: xsrf_token}))
  2148. chapters = self._extract_chapters(description_original, video_duration)
  2149. # Look for the DASH manifest
  2150. if self._downloader.params.get('youtube_include_dash_manifest', True):
  2151. dash_mpd_fatal = True
  2152. for mpd_url in dash_mpds:
  2153. dash_formats = {}
  2154. try:
  2155. def decrypt_sig(mobj):
  2156. s = mobj.group(1)
  2157. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  2158. return '/signature/%s' % dec_s
  2159. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  2160. for df in self._extract_mpd_formats(
  2161. mpd_url, video_id, fatal=dash_mpd_fatal,
  2162. formats_dict=self._formats):
  2163. if not df.get('filesize'):
  2164. df['filesize'] = _extract_filesize(df['url'])
  2165. # Do not overwrite DASH format found in some previous DASH manifest
  2166. if df['format_id'] not in dash_formats:
  2167. dash_formats[df['format_id']] = df
  2168. # Additional DASH manifests may end up in HTTP Error 403 therefore
  2169. # allow them to fail without bug report message if we already have
  2170. # some DASH manifest succeeded. This is temporary workaround to reduce
  2171. # burst of bug reports until we figure out the reason and whether it
  2172. # can be fixed at all.
  2173. dash_mpd_fatal = False
  2174. except (ExtractorError, KeyError) as e:
  2175. self.report_warning(
  2176. 'Skipping DASH manifest: %r' % e, video_id)
  2177. if dash_formats:
  2178. # Remove the formats we found through non-DASH, they
  2179. # contain less info and it can be wrong, because we use
  2180. # fixed values (for example the resolution). See
  2181. # https://github.com/ytdl-org/youtube-dl/issues/5774 for an
  2182. # example.
  2183. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  2184. formats.extend(dash_formats.values())
  2185. # Check for malformed aspect ratio
  2186. stretched_m = re.search(
  2187. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  2188. video_webpage)
  2189. if stretched_m:
  2190. w = float(stretched_m.group('w'))
  2191. h = float(stretched_m.group('h'))
  2192. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  2193. # We will only process correct ratios.
  2194. if w > 0 and h > 0:
  2195. ratio = w / h
  2196. for f in formats:
  2197. if f.get('vcodec') != 'none':
  2198. f['stretched_ratio'] = ratio
  2199. if not formats:
  2200. if 'reason' in video_info:
  2201. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  2202. regions_allowed = self._html_search_meta(
  2203. 'regionsAllowed', video_webpage, default=None)
  2204. countries = regions_allowed.split(',') if regions_allowed else None
  2205. self.raise_geo_restricted(
  2206. msg=video_info['reason'][0], countries=countries)
  2207. reason = video_info['reason'][0]
  2208. if 'Invalid parameters' in reason:
  2209. unavailable_message = extract_unavailable_message()
  2210. if unavailable_message:
  2211. reason = unavailable_message
  2212. raise ExtractorError(
  2213. 'YouTube said: %s' % reason,
  2214. expected=True, video_id=video_id)
  2215. if video_info.get('license_info') or try_get(player_response, lambda x: x['streamingData']['licenseInfos']):
  2216. raise ExtractorError('This video is DRM protected.', expected=True)
  2217. self._sort_formats(formats)
  2218. self.mark_watched(video_id, video_info, player_response)
  2219. return {
  2220. 'id': video_id,
  2221. 'uploader': video_uploader,
  2222. 'uploader_id': video_uploader_id,
  2223. 'uploader_url': video_uploader_url,
  2224. 'channel_id': channel_id,
  2225. 'channel_url': channel_url,
  2226. 'upload_date': upload_date,
  2227. 'license': video_license,
  2228. 'creator': video_creator or artist,
  2229. 'title': video_title,
  2230. 'alt_title': video_alt_title or track,
  2231. 'thumbnail': video_thumbnail,
  2232. 'description': video_description,
  2233. 'categories': video_categories,
  2234. 'tags': video_tags,
  2235. 'subtitles': video_subtitles,
  2236. 'automatic_captions': automatic_captions,
  2237. 'duration': video_duration,
  2238. 'age_limit': 18 if age_gate else 0,
  2239. 'annotations': video_annotations,
  2240. 'chapters': chapters,
  2241. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  2242. 'view_count': view_count,
  2243. 'like_count': like_count,
  2244. 'dislike_count': dislike_count,
  2245. 'average_rating': average_rating,
  2246. 'formats': formats,
  2247. 'is_live': is_live,
  2248. 'start_time': start_time,
  2249. 'end_time': end_time,
  2250. 'series': series,
  2251. 'season_number': season_number,
  2252. 'episode_number': episode_number,
  2253. 'track': track,
  2254. 'artist': artist,
  2255. 'album': album,
  2256. 'release_date': release_date,
  2257. 'release_year': release_year,
  2258. }
  2259. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  2260. IE_DESC = 'YouTube.com playlists'
  2261. _VALID_URL = r"""(?x)(?:
  2262. (?:https?://)?
  2263. (?:\w+\.)?
  2264. (?:
  2265. (?:
  2266. youtube(?:kids)?\.com|
  2267. invidio\.us
  2268. )
  2269. /
  2270. (?:
  2271. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
  2272. \? (?:.*?[&;])*? (?:p|a|list)=
  2273. | p/
  2274. )|
  2275. youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
  2276. )
  2277. (
  2278. (?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)?[0-9A-Za-z-_]{10,}
  2279. # Top tracks, they can also include dots
  2280. |(?:MC)[\w\.]*
  2281. )
  2282. .*
  2283. |
  2284. (%(playlist_id)s)
  2285. )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2286. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  2287. _VIDEO_RE_TPL = r'href="\s*/watch\?v=%s(?:&amp;(?:[^"]*?index=(?P<index>\d+))?(?:[^>]+>(?P<title>[^<]+))?)?'
  2288. _VIDEO_RE = _VIDEO_RE_TPL % r'(?P<id>[0-9A-Za-z_-]{11})'
  2289. IE_NAME = 'youtube:playlist'
  2290. _TESTS = [{
  2291. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2292. 'info_dict': {
  2293. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2294. 'uploader': 'Sergey M.',
  2295. 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2296. 'title': 'youtube-dl public playlist',
  2297. },
  2298. 'playlist_count': 1,
  2299. }, {
  2300. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2301. 'info_dict': {
  2302. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2303. 'uploader': 'Sergey M.',
  2304. 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2305. 'title': 'youtube-dl empty playlist',
  2306. },
  2307. 'playlist_count': 0,
  2308. }, {
  2309. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2310. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2311. 'info_dict': {
  2312. 'title': '29C3: Not my department',
  2313. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2314. 'uploader': 'Christiaan008',
  2315. 'uploader_id': 'ChRiStIaAn008',
  2316. },
  2317. 'playlist_count': 96,
  2318. }, {
  2319. 'note': 'issue #673',
  2320. 'url': 'PLBB231211A4F62143',
  2321. 'info_dict': {
  2322. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2323. 'id': 'PLBB231211A4F62143',
  2324. 'uploader': 'Wickydoo',
  2325. 'uploader_id': 'Wickydoo',
  2326. },
  2327. 'playlist_mincount': 26,
  2328. }, {
  2329. 'note': 'Large playlist',
  2330. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2331. 'info_dict': {
  2332. 'title': 'Uploads from Cauchemar',
  2333. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2334. 'uploader': 'Cauchemar',
  2335. 'uploader_id': 'Cauchemar89',
  2336. },
  2337. 'playlist_mincount': 799,
  2338. }, {
  2339. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2340. 'info_dict': {
  2341. 'title': 'YDL_safe_search',
  2342. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2343. },
  2344. 'playlist_count': 2,
  2345. 'skip': 'This playlist is private',
  2346. }, {
  2347. 'note': 'embedded',
  2348. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2349. 'playlist_count': 4,
  2350. 'info_dict': {
  2351. 'title': 'JODA15',
  2352. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2353. 'uploader': 'milan',
  2354. 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  2355. }
  2356. }, {
  2357. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2358. 'playlist_mincount': 485,
  2359. 'info_dict': {
  2360. 'title': '2018 Chinese New Singles (11/6 updated)',
  2361. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2362. 'uploader': 'LBK',
  2363. 'uploader_id': 'sdragonfang',
  2364. }
  2365. }, {
  2366. 'note': 'Embedded SWF player',
  2367. 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  2368. 'playlist_count': 4,
  2369. 'info_dict': {
  2370. 'title': 'JODA7',
  2371. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  2372. },
  2373. 'skip': 'This playlist does not exist',
  2374. }, {
  2375. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2376. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2377. 'info_dict': {
  2378. 'title': 'Uploads from Interstellar Movie',
  2379. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2380. 'uploader': 'Interstellar Movie',
  2381. 'uploader_id': 'InterstellarMovie1',
  2382. },
  2383. 'playlist_mincount': 21,
  2384. }, {
  2385. # Playlist URL that does not actually serve a playlist
  2386. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2387. 'info_dict': {
  2388. 'id': 'FqZTN594JQw',
  2389. 'ext': 'webm',
  2390. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2391. 'uploader': 'STREEM',
  2392. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2393. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2394. 'upload_date': '20150526',
  2395. 'license': 'Standard YouTube License',
  2396. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2397. 'categories': ['People & Blogs'],
  2398. 'tags': list,
  2399. 'view_count': int,
  2400. 'like_count': int,
  2401. 'dislike_count': int,
  2402. },
  2403. 'params': {
  2404. 'skip_download': True,
  2405. },
  2406. 'skip': 'This video is not available.',
  2407. 'add_ie': [YoutubeIE.ie_key()],
  2408. }, {
  2409. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2410. 'info_dict': {
  2411. 'id': 'yeWKywCrFtk',
  2412. 'ext': 'mp4',
  2413. 'title': 'Small Scale Baler and Braiding Rugs',
  2414. 'uploader': 'Backus-Page House Museum',
  2415. 'uploader_id': 'backuspagemuseum',
  2416. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2417. 'upload_date': '20161008',
  2418. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2419. 'categories': ['Nonprofits & Activism'],
  2420. 'tags': list,
  2421. 'like_count': int,
  2422. 'dislike_count': int,
  2423. },
  2424. 'params': {
  2425. 'noplaylist': True,
  2426. 'skip_download': True,
  2427. },
  2428. }, {
  2429. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2430. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2431. 'info_dict': {
  2432. 'title': 'Data Analysis with Dr Mike Pound',
  2433. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2434. 'uploader_id': 'Computerphile',
  2435. 'uploader': 'Computerphile',
  2436. },
  2437. 'playlist_mincount': 11,
  2438. }, {
  2439. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  2440. 'only_matching': True,
  2441. }, {
  2442. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2443. 'only_matching': True,
  2444. }, {
  2445. # music album playlist
  2446. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2447. 'only_matching': True,
  2448. }, {
  2449. 'url': 'https://invidio.us/playlist?list=PLDIoUOhQQPlXr63I_vwF9GD8sAKh77dWU',
  2450. 'only_matching': True,
  2451. }, {
  2452. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  2453. 'only_matching': True,
  2454. }]
  2455. def _real_initialize(self):
  2456. self._login()
  2457. def extract_videos_from_page(self, page):
  2458. ids_in_page = []
  2459. titles_in_page = []
  2460. for item in re.findall(
  2461. r'(<[^>]*\bdata-video-id\s*=\s*["\'][0-9A-Za-z_-]{11}[^>]+>)', page):
  2462. attrs = extract_attributes(item)
  2463. video_id = attrs['data-video-id']
  2464. video_title = unescapeHTML(attrs.get('data-title'))
  2465. if video_title:
  2466. video_title = video_title.strip()
  2467. ids_in_page.append(video_id)
  2468. titles_in_page.append(video_title)
  2469. # Fallback with old _VIDEO_RE
  2470. self.extract_videos_from_page_impl(
  2471. self._VIDEO_RE, page, ids_in_page, titles_in_page)
  2472. # Relaxed fallbacks
  2473. self.extract_videos_from_page_impl(
  2474. r'href="\s*/watch\?v\s*=\s*(?P<id>[0-9A-Za-z_-]{11})', page,
  2475. ids_in_page, titles_in_page)
  2476. self.extract_videos_from_page_impl(
  2477. r'data-video-ids\s*=\s*["\'](?P<id>[0-9A-Za-z_-]{11})', page,
  2478. ids_in_page, titles_in_page)
  2479. return zip(ids_in_page, titles_in_page)
  2480. def _extract_mix(self, playlist_id):
  2481. # The mixes are generated from a single video
  2482. # the id of the playlist is just 'RD' + video_id
  2483. ids = []
  2484. last_id = playlist_id[-11:]
  2485. for n in itertools.count(1):
  2486. url = 'https://youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
  2487. webpage = self._download_webpage(
  2488. url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
  2489. new_ids = orderedSet(re.findall(
  2490. r'''(?xs)data-video-username=".*?".*?
  2491. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  2492. webpage))
  2493. # Fetch new pages until all the videos are repeated, it seems that
  2494. # there are always 51 unique videos.
  2495. new_ids = [_id for _id in new_ids if _id not in ids]
  2496. if not new_ids:
  2497. break
  2498. ids.extend(new_ids)
  2499. last_id = ids[-1]
  2500. url_results = self._ids_to_results(ids)
  2501. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  2502. title_span = (
  2503. search_title('playlist-title')
  2504. or search_title('title long-title')
  2505. or search_title('title'))
  2506. title = clean_html(title_span)
  2507. return self.playlist_result(url_results, playlist_id, title)
  2508. def _extract_playlist(self, playlist_id):
  2509. url = self._TEMPLATE_URL % playlist_id
  2510. page = self._download_webpage(url, playlist_id)
  2511. # the yt-alert-message now has tabindex attribute (see https://github.com/ytdl-org/youtube-dl/issues/11604)
  2512. for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
  2513. match = match.strip()
  2514. # Check if the playlist exists or is private
  2515. mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
  2516. if mobj:
  2517. reason = mobj.group('reason')
  2518. message = 'This playlist %s' % reason
  2519. if 'private' in reason:
  2520. message += ', use --username or --netrc to access it'
  2521. message += '.'
  2522. raise ExtractorError(message, expected=True)
  2523. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  2524. raise ExtractorError(
  2525. 'Invalid parameters. Maybe URL is incorrect.',
  2526. expected=True)
  2527. elif re.match(r'[^<]*Choose your language[^<]*', match):
  2528. continue
  2529. else:
  2530. self.report_warning('Youtube gives an alert message: ' + match)
  2531. playlist_title = self._html_search_regex(
  2532. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  2533. page, 'title', default=None)
  2534. _UPLOADER_BASE = r'class=["\']pl-header-details[^>]+>\s*<li>\s*<a[^>]+\bhref='
  2535. uploader = self._html_search_regex(
  2536. r'%s["\']/(?:user|channel)/[^>]+>([^<]+)' % _UPLOADER_BASE,
  2537. page, 'uploader', default=None)
  2538. mobj = re.search(
  2539. r'%s(["\'])(?P<path>/(?:user|channel)/(?P<uploader_id>.+?))\1' % _UPLOADER_BASE,
  2540. page)
  2541. if mobj:
  2542. uploader_id = mobj.group('uploader_id')
  2543. uploader_url = compat_urlparse.urljoin(url, mobj.group('path'))
  2544. else:
  2545. uploader_id = uploader_url = None
  2546. has_videos = True
  2547. if not playlist_title:
  2548. try:
  2549. # Some playlist URLs don't actually serve a playlist (e.g.
  2550. # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
  2551. next(self._entries(page, playlist_id))
  2552. except StopIteration:
  2553. has_videos = False
  2554. playlist = self.playlist_result(
  2555. self._entries(page, playlist_id), playlist_id, playlist_title)
  2556. playlist.update({
  2557. 'uploader': uploader,
  2558. 'uploader_id': uploader_id,
  2559. 'uploader_url': uploader_url,
  2560. })
  2561. return has_videos, playlist
  2562. def _check_download_just_video(self, url, playlist_id):
  2563. # Check if it's a video-specific URL
  2564. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  2565. video_id = query_dict.get('v', [None])[0] or self._search_regex(
  2566. r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
  2567. 'video id', default=None)
  2568. if video_id:
  2569. if self._downloader.params.get('noplaylist'):
  2570. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2571. return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
  2572. else:
  2573. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2574. return video_id, None
  2575. return None, None
  2576. def _real_extract(self, url):
  2577. # Extract playlist id
  2578. mobj = re.match(self._VALID_URL, url)
  2579. if mobj is None:
  2580. raise ExtractorError('Invalid URL: %s' % url)
  2581. playlist_id = mobj.group(1) or mobj.group(2)
  2582. video_id, video = self._check_download_just_video(url, playlist_id)
  2583. if video:
  2584. return video
  2585. if playlist_id.startswith(('RD', 'UL', 'PU')):
  2586. # Mixes require a custom extraction process
  2587. return self._extract_mix(playlist_id)
  2588. has_videos, playlist = self._extract_playlist(playlist_id)
  2589. if has_videos or not video_id:
  2590. return playlist
  2591. # Some playlist URLs don't actually serve a playlist (see
  2592. # https://github.com/ytdl-org/youtube-dl/issues/10537).
  2593. # Fallback to plain video extraction if there is a video id
  2594. # along with playlist id.
  2595. return self.url_result(video_id, 'Youtube', video_id=video_id)
  2596. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  2597. IE_DESC = 'YouTube.com channels'
  2598. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie|kids)?\.com|(?:www\.)?invidio\.us)/channel/(?P<id>[0-9A-Za-z_-]+)'
  2599. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  2600. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  2601. IE_NAME = 'youtube:channel'
  2602. _TESTS = [{
  2603. 'note': 'paginated channel',
  2604. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  2605. 'playlist_mincount': 91,
  2606. 'info_dict': {
  2607. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  2608. 'title': 'Uploads from lex will',
  2609. 'uploader': 'lex will',
  2610. 'uploader_id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2611. }
  2612. }, {
  2613. 'note': 'Age restricted channel',
  2614. # from https://www.youtube.com/user/DeusExOfficial
  2615. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  2616. 'playlist_mincount': 64,
  2617. 'info_dict': {
  2618. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  2619. 'title': 'Uploads from Deus Ex',
  2620. 'uploader': 'Deus Ex',
  2621. 'uploader_id': 'DeusExOfficial',
  2622. },
  2623. }, {
  2624. 'url': 'https://invidio.us/channel/UC23qupoDRn9YOAVzeoxjOQA',
  2625. 'only_matching': True,
  2626. }, {
  2627. 'url': 'https://www.youtubekids.com/channel/UCyu8StPfZWapR6rfW_JgqcA',
  2628. 'only_matching': True,
  2629. }]
  2630. @classmethod
  2631. def suitable(cls, url):
  2632. return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
  2633. else super(YoutubeChannelIE, cls).suitable(url))
  2634. def _build_template_url(self, url, channel_id):
  2635. return self._TEMPLATE_URL % channel_id
  2636. def _real_extract(self, url):
  2637. channel_id = self._match_id(url)
  2638. url = self._build_template_url(url, channel_id)
  2639. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  2640. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  2641. # otherwise fallback on channel by page extraction
  2642. channel_page = self._download_webpage(
  2643. url + '?view=57', channel_id,
  2644. 'Downloading channel page', fatal=False)
  2645. if channel_page is False:
  2646. channel_playlist_id = False
  2647. else:
  2648. channel_playlist_id = self._html_search_meta(
  2649. 'channelId', channel_page, 'channel id', default=None)
  2650. if not channel_playlist_id:
  2651. channel_url = self._html_search_meta(
  2652. ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
  2653. channel_page, 'channel url', default=None)
  2654. if channel_url:
  2655. channel_playlist_id = self._search_regex(
  2656. r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
  2657. channel_url, 'channel id', default=None)
  2658. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  2659. playlist_id = 'UU' + channel_playlist_id[2:]
  2660. return self.url_result(
  2661. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  2662. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  2663. autogenerated = re.search(r'''(?x)
  2664. class="[^"]*?(?:
  2665. channel-header-autogenerated-label|
  2666. yt-channel-title-autogenerated
  2667. )[^"]*"''', channel_page) is not None
  2668. if autogenerated:
  2669. # The videos are contained in a single page
  2670. # the ajax pages can't be used, they are empty
  2671. entries = [
  2672. self.url_result(
  2673. video_id, 'Youtube', video_id=video_id,
  2674. video_title=video_title)
  2675. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  2676. return self.playlist_result(entries, channel_id)
  2677. try:
  2678. next(self._entries(channel_page, channel_id))
  2679. except StopIteration:
  2680. alert_message = self._html_search_regex(
  2681. r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
  2682. channel_page, 'alert', default=None, group='alert')
  2683. if alert_message:
  2684. raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
  2685. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  2686. class YoutubeUserIE(YoutubeChannelIE):
  2687. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  2688. _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:(?P<user>user|c)/)?(?!(?:attribution_link|watch|results|shared)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
  2689. _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
  2690. IE_NAME = 'youtube:user'
  2691. _TESTS = [{
  2692. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  2693. 'playlist_mincount': 320,
  2694. 'info_dict': {
  2695. 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
  2696. 'title': 'Uploads from The Linux Foundation',
  2697. 'uploader': 'The Linux Foundation',
  2698. 'uploader_id': 'TheLinuxFoundation',
  2699. }
  2700. }, {
  2701. # Only available via https://www.youtube.com/c/12minuteathlete/videos
  2702. # but not https://www.youtube.com/user/12minuteathlete/videos
  2703. 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
  2704. 'playlist_mincount': 249,
  2705. 'info_dict': {
  2706. 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
  2707. 'title': 'Uploads from 12 Minute Athlete',
  2708. 'uploader': '12 Minute Athlete',
  2709. 'uploader_id': 'the12minuteathlete',
  2710. }
  2711. }, {
  2712. 'url': 'ytuser:phihag',
  2713. 'only_matching': True,
  2714. }, {
  2715. 'url': 'https://www.youtube.com/c/gametrailers',
  2716. 'only_matching': True,
  2717. }, {
  2718. 'url': 'https://www.youtube.com/gametrailers',
  2719. 'only_matching': True,
  2720. }, {
  2721. # This channel is not available, geo restricted to JP
  2722. 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
  2723. 'only_matching': True,
  2724. }]
  2725. @classmethod
  2726. def suitable(cls, url):
  2727. # Don't return True if the url can be extracted with other youtube
  2728. # extractor, the regex would is too permissive and it would match.
  2729. other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
  2730. if any(ie.suitable(url) for ie in other_yt_ies):
  2731. return False
  2732. else:
  2733. return super(YoutubeUserIE, cls).suitable(url)
  2734. def _build_template_url(self, url, channel_id):
  2735. mobj = re.match(self._VALID_URL, url)
  2736. return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
  2737. class YoutubeLiveIE(YoutubeBaseInfoExtractor):
  2738. IE_DESC = 'YouTube.com live streams'
  2739. _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
  2740. IE_NAME = 'youtube:live'
  2741. _TESTS = [{
  2742. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2743. 'info_dict': {
  2744. 'id': 'a48o2S1cPoo',
  2745. 'ext': 'mp4',
  2746. 'title': 'The Young Turks - Live Main Show',
  2747. 'uploader': 'The Young Turks',
  2748. 'uploader_id': 'TheYoungTurks',
  2749. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2750. 'upload_date': '20150715',
  2751. 'license': 'Standard YouTube License',
  2752. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2753. 'categories': ['News & Politics'],
  2754. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2755. 'like_count': int,
  2756. 'dislike_count': int,
  2757. },
  2758. 'params': {
  2759. 'skip_download': True,
  2760. },
  2761. }, {
  2762. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2763. 'only_matching': True,
  2764. }, {
  2765. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2766. 'only_matching': True,
  2767. }, {
  2768. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2769. 'only_matching': True,
  2770. }]
  2771. def _real_extract(self, url):
  2772. mobj = re.match(self._VALID_URL, url)
  2773. channel_id = mobj.group('id')
  2774. base_url = mobj.group('base_url')
  2775. webpage = self._download_webpage(url, channel_id, fatal=False)
  2776. if webpage:
  2777. page_type = self._og_search_property(
  2778. 'type', webpage, 'page type', default='')
  2779. video_id = self._html_search_meta(
  2780. 'videoId', webpage, 'video id', default=None)
  2781. if page_type.startswith('video') and video_id and re.match(
  2782. r'^[0-9A-Za-z_-]{11}$', video_id):
  2783. return self.url_result(video_id, YoutubeIE.ie_key())
  2784. return self.url_result(base_url)
  2785. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  2786. IE_DESC = 'YouTube.com user/channel playlists'
  2787. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  2788. IE_NAME = 'youtube:playlists'
  2789. _TESTS = [{
  2790. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2791. 'playlist_mincount': 4,
  2792. 'info_dict': {
  2793. 'id': 'ThirstForScience',
  2794. 'title': 'ThirstForScience',
  2795. },
  2796. }, {
  2797. # with "Load more" button
  2798. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2799. 'playlist_mincount': 70,
  2800. 'info_dict': {
  2801. 'id': 'igorkle1',
  2802. 'title': 'Игорь Клейнер',
  2803. },
  2804. }, {
  2805. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  2806. 'playlist_mincount': 17,
  2807. 'info_dict': {
  2808. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  2809. 'title': 'Chem Player',
  2810. },
  2811. 'skip': 'Blocked',
  2812. }]
  2813. class YoutubeSearchBaseInfoExtractor(YoutubePlaylistBaseInfoExtractor):
  2814. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
  2815. class YoutubeSearchIE(SearchInfoExtractor, YoutubeSearchBaseInfoExtractor):
  2816. IE_DESC = 'YouTube.com searches'
  2817. # there doesn't appear to be a real limit, for example if you search for
  2818. # 'python' you get more than 8.000.000 results
  2819. _MAX_RESULTS = float('inf')
  2820. IE_NAME = 'youtube:search'
  2821. _SEARCH_KEY = 'ytsearch'
  2822. _EXTRA_QUERY_ARGS = {}
  2823. _TESTS = []
  2824. def _get_n_results(self, query, n):
  2825. """Get a specified number of results for a query"""
  2826. videos = []
  2827. limit = n
  2828. url_query = {
  2829. 'search_query': query.encode('utf-8'),
  2830. }
  2831. url_query.update(self._EXTRA_QUERY_ARGS)
  2832. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse_urlencode(url_query)
  2833. for pagenum in itertools.count(1):
  2834. data = self._download_json(
  2835. result_url, video_id='query "%s"' % query,
  2836. note='Downloading page %s' % pagenum,
  2837. errnote='Unable to download API page',
  2838. query={'spf': 'navigate'})
  2839. html_content = data[1]['body']['content']
  2840. if 'class="search-message' in html_content:
  2841. raise ExtractorError(
  2842. '[youtube] No video results', expected=True)
  2843. new_videos = list(self._process_page(html_content))
  2844. videos += new_videos
  2845. if not new_videos or len(videos) > limit:
  2846. break
  2847. next_link = self._html_search_regex(
  2848. r'href="(/results\?[^"]*\bsp=[^"]+)"[^>]*>\s*<span[^>]+class="[^"]*\byt-uix-button-content\b[^"]*"[^>]*>Next',
  2849. html_content, 'next link', default=None)
  2850. if next_link is None:
  2851. break
  2852. result_url = compat_urlparse.urljoin('https://www.youtube.com/', next_link)
  2853. if len(videos) > n:
  2854. videos = videos[:n]
  2855. return self.playlist_result(videos, query)
  2856. class YoutubeSearchDateIE(YoutubeSearchIE):
  2857. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  2858. _SEARCH_KEY = 'ytsearchdate'
  2859. IE_DESC = 'YouTube.com searches, newest videos first'
  2860. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  2861. class YoutubeSearchURLIE(YoutubeSearchBaseInfoExtractor):
  2862. IE_DESC = 'YouTube.com search URLs'
  2863. IE_NAME = 'youtube:search_url'
  2864. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  2865. _TESTS = [{
  2866. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  2867. 'playlist_mincount': 5,
  2868. 'info_dict': {
  2869. 'title': 'youtube-dl test video',
  2870. }
  2871. }, {
  2872. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  2873. 'only_matching': True,
  2874. }]
  2875. def _real_extract(self, url):
  2876. mobj = re.match(self._VALID_URL, url)
  2877. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  2878. webpage = self._download_webpage(url, query)
  2879. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  2880. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  2881. IE_DESC = 'YouTube.com (multi-season) shows'
  2882. _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
  2883. IE_NAME = 'youtube:show'
  2884. _TESTS = [{
  2885. 'url': 'https://www.youtube.com/show/airdisasters',
  2886. 'playlist_mincount': 5,
  2887. 'info_dict': {
  2888. 'id': 'airdisasters',
  2889. 'title': 'Air Disasters',
  2890. }
  2891. }]
  2892. def _real_extract(self, url):
  2893. playlist_id = self._match_id(url)
  2894. return super(YoutubeShowIE, self)._real_extract(
  2895. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  2896. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  2897. """
  2898. Base class for feed extractors
  2899. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  2900. """
  2901. _LOGIN_REQUIRED = True
  2902. @property
  2903. def IE_NAME(self):
  2904. return 'youtube:%s' % self._FEED_NAME
  2905. def _real_initialize(self):
  2906. self._login()
  2907. def _entries(self, page):
  2908. # The extraction process is the same as for playlists, but the regex
  2909. # for the video ids doesn't contain an index
  2910. ids = []
  2911. more_widget_html = content_html = page
  2912. for page_num in itertools.count(1):
  2913. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  2914. # 'recommended' feed has infinite 'load more' and each new portion spins
  2915. # the same videos in (sometimes) slightly different order, so we'll check
  2916. # for unicity and break when portion has no new videos
  2917. new_ids = list(filter(lambda video_id: video_id not in ids, orderedSet(matches)))
  2918. if not new_ids:
  2919. break
  2920. ids.extend(new_ids)
  2921. for entry in self._ids_to_results(new_ids):
  2922. yield entry
  2923. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  2924. if not mobj:
  2925. break
  2926. more = self._download_json(
  2927. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  2928. 'Downloading page #%s' % page_num,
  2929. transform_source=uppercase_escape)
  2930. content_html = more['content_html']
  2931. more_widget_html = more['load_more_widget_html']
  2932. def _real_extract(self, url):
  2933. page = self._download_webpage(
  2934. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  2935. self._PLAYLIST_TITLE)
  2936. return self.playlist_result(
  2937. self._entries(page), playlist_title=self._PLAYLIST_TITLE)
  2938. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  2939. IE_NAME = 'youtube:watchlater'
  2940. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  2941. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  2942. _TESTS = [{
  2943. 'url': 'https://www.youtube.com/playlist?list=WL',
  2944. 'only_matching': True,
  2945. }, {
  2946. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  2947. 'only_matching': True,
  2948. }]
  2949. def _real_extract(self, url):
  2950. _, video = self._check_download_just_video(url, 'WL')
  2951. if video:
  2952. return video
  2953. _, playlist = self._extract_playlist('WL')
  2954. return playlist
  2955. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2956. IE_NAME = 'youtube:favorites'
  2957. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2958. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2959. _LOGIN_REQUIRED = True
  2960. def _real_extract(self, url):
  2961. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  2962. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  2963. return self.url_result(playlist_id, 'YoutubePlaylist')
  2964. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2965. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2966. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  2967. _FEED_NAME = 'recommended'
  2968. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  2969. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2970. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2971. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  2972. _FEED_NAME = 'subscriptions'
  2973. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  2974. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2975. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2976. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
  2977. _FEED_NAME = 'history'
  2978. _PLAYLIST_TITLE = 'Youtube History'
  2979. class YoutubeTruncatedURLIE(InfoExtractor):
  2980. IE_NAME = 'youtube:truncated_url'
  2981. IE_DESC = False # Do not list
  2982. _VALID_URL = r'''(?x)
  2983. (?:https?://)?
  2984. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  2985. (?:watch\?(?:
  2986. feature=[a-z_]+|
  2987. annotation_id=annotation_[^&]+|
  2988. x-yt-cl=[0-9]+|
  2989. hl=[^&]*|
  2990. t=[0-9]+
  2991. )?
  2992. |
  2993. attribution_link\?a=[^&]+
  2994. )
  2995. $
  2996. '''
  2997. _TESTS = [{
  2998. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  2999. 'only_matching': True,
  3000. }, {
  3001. 'url': 'https://www.youtube.com/watch?',
  3002. 'only_matching': True,
  3003. }, {
  3004. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  3005. 'only_matching': True,
  3006. }, {
  3007. 'url': 'https://www.youtube.com/watch?feature=foo',
  3008. 'only_matching': True,
  3009. }, {
  3010. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  3011. 'only_matching': True,
  3012. }, {
  3013. 'url': 'https://www.youtube.com/watch?t=2372',
  3014. 'only_matching': True,
  3015. }]
  3016. def _real_extract(self, url):
  3017. raise ExtractorError(
  3018. 'Did you forget to quote the URL? Remember that & is a meta '
  3019. 'character in most shells, so you want to put the URL in quotes, '
  3020. 'like youtube-dl '
  3021. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  3022. ' or simply youtube-dl BaW_jenozKc .',
  3023. expected=True)
  3024. class YoutubeTruncatedIDIE(InfoExtractor):
  3025. IE_NAME = 'youtube:truncated_id'
  3026. IE_DESC = False # Do not list
  3027. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  3028. _TESTS = [{
  3029. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  3030. 'only_matching': True,
  3031. }]
  3032. def _real_extract(self, url):
  3033. video_id = self._match_id(url)
  3034. raise ExtractorError(
  3035. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  3036. expected=True)