youtube.py 143 KB

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