youtube.py 142 KB

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