youtube.py 146 KB

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