youtube.py 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194
  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'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1232. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1233. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*c\s*&&\s*d\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?(?P<sig>[a-zA-Z0-9$]+)\(',
  1234. r'\bc\s*&&\s*d\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1235. r'\bc\s*&&\s*d\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
  1236. jscode, 'Initial JS player signature function name', group='sig')
  1237. jsi = JSInterpreter(jscode)
  1238. initial_function = jsi.extract_function(funcname)
  1239. return lambda s: initial_function([s])
  1240. def _parse_sig_swf(self, file_contents):
  1241. swfi = SWFInterpreter(file_contents)
  1242. TARGET_CLASSNAME = 'SignatureDecipher'
  1243. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  1244. initial_function = swfi.extract_function(searched_class, 'decipher')
  1245. return lambda s: initial_function([s])
  1246. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  1247. """Turn the encrypted s field into a working signature"""
  1248. if player_url is None:
  1249. raise ExtractorError('Cannot decrypt signature without player_url')
  1250. if player_url.startswith('//'):
  1251. player_url = 'https:' + player_url
  1252. elif not re.match(r'https?://', player_url):
  1253. player_url = compat_urlparse.urljoin(
  1254. 'https://www.youtube.com', player_url)
  1255. try:
  1256. player_id = (player_url, self._signature_cache_id(s))
  1257. if player_id not in self._player_cache:
  1258. func = self._extract_signature_function(
  1259. video_id, player_url, s
  1260. )
  1261. self._player_cache[player_id] = func
  1262. func = self._player_cache[player_id]
  1263. if self._downloader.params.get('youtube_print_sig_code'):
  1264. self._print_sig_code(func, s)
  1265. return func(s)
  1266. except Exception as e:
  1267. tb = traceback.format_exc()
  1268. raise ExtractorError(
  1269. 'Signature extraction failed: ' + tb, cause=e)
  1270. def _get_subtitles(self, video_id, webpage):
  1271. try:
  1272. subs_doc = self._download_xml(
  1273. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1274. video_id, note=False)
  1275. except ExtractorError as err:
  1276. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  1277. return {}
  1278. sub_lang_list = {}
  1279. for track in subs_doc.findall('track'):
  1280. lang = track.attrib['lang_code']
  1281. if lang in sub_lang_list:
  1282. continue
  1283. sub_formats = []
  1284. for ext in self._SUBTITLE_FORMATS:
  1285. params = compat_urllib_parse_urlencode({
  1286. 'lang': lang,
  1287. 'v': video_id,
  1288. 'fmt': ext,
  1289. 'name': track.attrib['name'].encode('utf-8'),
  1290. })
  1291. sub_formats.append({
  1292. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  1293. 'ext': ext,
  1294. })
  1295. sub_lang_list[lang] = sub_formats
  1296. if not sub_lang_list:
  1297. self._downloader.report_warning('video doesn\'t have subtitles')
  1298. return {}
  1299. return sub_lang_list
  1300. def _get_ytplayer_config(self, video_id, webpage):
  1301. patterns = (
  1302. # User data may contain arbitrary character sequences that may affect
  1303. # JSON extraction with regex, e.g. when '};' is contained the second
  1304. # regex won't capture the whole JSON. Yet working around by trying more
  1305. # concrete regex first keeping in mind proper quoted string handling
  1306. # to be implemented in future that will replace this workaround (see
  1307. # https://github.com/ytdl-org/youtube-dl/issues/7468,
  1308. # https://github.com/ytdl-org/youtube-dl/pull/7599)
  1309. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  1310. r';ytplayer\.config\s*=\s*({.+?});',
  1311. )
  1312. config = self._search_regex(
  1313. patterns, webpage, 'ytplayer.config', default=None)
  1314. if config:
  1315. return self._parse_json(
  1316. uppercase_escape(config), video_id, fatal=False)
  1317. def _get_automatic_captions(self, video_id, webpage):
  1318. """We need the webpage for getting the captions url, pass it as an
  1319. argument to speed up the process."""
  1320. self.to_screen('%s: Looking for automatic captions' % video_id)
  1321. player_config = self._get_ytplayer_config(video_id, webpage)
  1322. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  1323. if not player_config:
  1324. self._downloader.report_warning(err_msg)
  1325. return {}
  1326. try:
  1327. args = player_config['args']
  1328. caption_url = args.get('ttsurl')
  1329. if caption_url:
  1330. timestamp = args['timestamp']
  1331. # We get the available subtitles
  1332. list_params = compat_urllib_parse_urlencode({
  1333. 'type': 'list',
  1334. 'tlangs': 1,
  1335. 'asrs': 1,
  1336. })
  1337. list_url = caption_url + '&' + list_params
  1338. caption_list = self._download_xml(list_url, video_id)
  1339. original_lang_node = caption_list.find('track')
  1340. if original_lang_node is None:
  1341. self._downloader.report_warning('Video doesn\'t have automatic captions')
  1342. return {}
  1343. original_lang = original_lang_node.attrib['lang_code']
  1344. caption_kind = original_lang_node.attrib.get('kind', '')
  1345. sub_lang_list = {}
  1346. for lang_node in caption_list.findall('target'):
  1347. sub_lang = lang_node.attrib['lang_code']
  1348. sub_formats = []
  1349. for ext in self._SUBTITLE_FORMATS:
  1350. params = compat_urllib_parse_urlencode({
  1351. 'lang': original_lang,
  1352. 'tlang': sub_lang,
  1353. 'fmt': ext,
  1354. 'ts': timestamp,
  1355. 'kind': caption_kind,
  1356. })
  1357. sub_formats.append({
  1358. 'url': caption_url + '&' + params,
  1359. 'ext': ext,
  1360. })
  1361. sub_lang_list[sub_lang] = sub_formats
  1362. return sub_lang_list
  1363. def make_captions(sub_url, sub_langs):
  1364. parsed_sub_url = compat_urllib_parse_urlparse(sub_url)
  1365. caption_qs = compat_parse_qs(parsed_sub_url.query)
  1366. captions = {}
  1367. for sub_lang in sub_langs:
  1368. sub_formats = []
  1369. for ext in self._SUBTITLE_FORMATS:
  1370. caption_qs.update({
  1371. 'tlang': [sub_lang],
  1372. 'fmt': [ext],
  1373. })
  1374. sub_url = compat_urlparse.urlunparse(parsed_sub_url._replace(
  1375. query=compat_urllib_parse_urlencode(caption_qs, True)))
  1376. sub_formats.append({
  1377. 'url': sub_url,
  1378. 'ext': ext,
  1379. })
  1380. captions[sub_lang] = sub_formats
  1381. return captions
  1382. # New captions format as of 22.06.2017
  1383. player_response = args.get('player_response')
  1384. if player_response and isinstance(player_response, compat_str):
  1385. player_response = self._parse_json(
  1386. player_response, video_id, fatal=False)
  1387. if player_response:
  1388. renderer = player_response['captions']['playerCaptionsTracklistRenderer']
  1389. base_url = renderer['captionTracks'][0]['baseUrl']
  1390. sub_lang_list = []
  1391. for lang in renderer['translationLanguages']:
  1392. lang_code = lang.get('languageCode')
  1393. if lang_code:
  1394. sub_lang_list.append(lang_code)
  1395. return make_captions(base_url, sub_lang_list)
  1396. # Some videos don't provide ttsurl but rather caption_tracks and
  1397. # caption_translation_languages (e.g. 20LmZk1hakA)
  1398. # Does not used anymore as of 22.06.2017
  1399. caption_tracks = args['caption_tracks']
  1400. caption_translation_languages = args['caption_translation_languages']
  1401. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1402. sub_lang_list = []
  1403. for lang in caption_translation_languages.split(','):
  1404. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1405. sub_lang = lang_qs.get('lc', [None])[0]
  1406. if sub_lang:
  1407. sub_lang_list.append(sub_lang)
  1408. return make_captions(caption_url, sub_lang_list)
  1409. # An extractor error can be raise by the download process if there are
  1410. # no automatic captions but there are subtitles
  1411. except (KeyError, IndexError, ExtractorError):
  1412. self._downloader.report_warning(err_msg)
  1413. return {}
  1414. def _mark_watched(self, video_id, video_info, player_response):
  1415. playback_url = url_or_none(try_get(
  1416. player_response,
  1417. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']) or try_get(
  1418. video_info, lambda x: x['videostats_playback_base_url'][0]))
  1419. if not playback_url:
  1420. return
  1421. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1422. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1423. # cpn generation algorithm is reverse engineered from base.js.
  1424. # In fact it works even with dummy cpn.
  1425. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1426. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1427. qs.update({
  1428. 'ver': ['2'],
  1429. 'cpn': [cpn],
  1430. })
  1431. playback_url = compat_urlparse.urlunparse(
  1432. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1433. self._download_webpage(
  1434. playback_url, video_id, 'Marking watched',
  1435. 'Unable to mark watched', fatal=False)
  1436. @staticmethod
  1437. def _extract_urls(webpage):
  1438. # Embedded YouTube player
  1439. entries = [
  1440. unescapeHTML(mobj.group('url'))
  1441. for mobj in re.finditer(r'''(?x)
  1442. (?:
  1443. <iframe[^>]+?src=|
  1444. data-video-url=|
  1445. <embed[^>]+?src=|
  1446. embedSWF\(?:\s*|
  1447. <object[^>]+data=|
  1448. new\s+SWFObject\(
  1449. )
  1450. (["\'])
  1451. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1452. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1453. \1''', webpage)]
  1454. # lazyYT YouTube embed
  1455. entries.extend(list(map(
  1456. unescapeHTML,
  1457. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  1458. # Wordpress "YouTube Video Importer" plugin
  1459. matches = re.findall(r'''(?x)<div[^>]+
  1460. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  1461. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  1462. entries.extend(m[-1] for m in matches)
  1463. return entries
  1464. @staticmethod
  1465. def _extract_url(webpage):
  1466. urls = YoutubeIE._extract_urls(webpage)
  1467. return urls[0] if urls else None
  1468. @classmethod
  1469. def extract_id(cls, url):
  1470. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1471. if mobj is None:
  1472. raise ExtractorError('Invalid URL: %s' % url)
  1473. video_id = mobj.group(2)
  1474. return video_id
  1475. def _extract_annotations(self, video_id):
  1476. return self._download_webpage(
  1477. 'https://www.youtube.com/annotations_invideo', video_id,
  1478. note='Downloading annotations',
  1479. errnote='Unable to download video annotations', fatal=False,
  1480. query={
  1481. 'features': 1,
  1482. 'legacy': 1,
  1483. 'video_id': video_id,
  1484. })
  1485. @staticmethod
  1486. def _extract_chapters(description, duration):
  1487. if not description:
  1488. return None
  1489. chapter_lines = re.findall(
  1490. r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
  1491. description)
  1492. if not chapter_lines:
  1493. return None
  1494. chapters = []
  1495. for next_num, (chapter_line, time_point) in enumerate(
  1496. chapter_lines, start=1):
  1497. start_time = parse_duration(time_point)
  1498. if start_time is None:
  1499. continue
  1500. if start_time > duration:
  1501. break
  1502. end_time = (duration if next_num == len(chapter_lines)
  1503. else parse_duration(chapter_lines[next_num][1]))
  1504. if end_time is None:
  1505. continue
  1506. if end_time > duration:
  1507. end_time = duration
  1508. if start_time > end_time:
  1509. break
  1510. chapter_title = re.sub(
  1511. r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
  1512. chapter_title = re.sub(r'\s+', ' ', chapter_title)
  1513. chapters.append({
  1514. 'start_time': start_time,
  1515. 'end_time': end_time,
  1516. 'title': chapter_title,
  1517. })
  1518. return chapters
  1519. def _real_extract(self, url):
  1520. url, smuggled_data = unsmuggle_url(url, {})
  1521. proto = (
  1522. 'http' if self._downloader.params.get('prefer_insecure', False)
  1523. else 'https')
  1524. start_time = None
  1525. end_time = None
  1526. parsed_url = compat_urllib_parse_urlparse(url)
  1527. for component in [parsed_url.fragment, parsed_url.query]:
  1528. query = compat_parse_qs(component)
  1529. if start_time is None and 't' in query:
  1530. start_time = parse_duration(query['t'][0])
  1531. if start_time is None and 'start' in query:
  1532. start_time = parse_duration(query['start'][0])
  1533. if end_time is None and 'end' in query:
  1534. end_time = parse_duration(query['end'][0])
  1535. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1536. mobj = re.search(self._NEXT_URL_RE, url)
  1537. if mobj:
  1538. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1539. video_id = self.extract_id(url)
  1540. # Get video webpage
  1541. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1542. video_webpage = self._download_webpage(url, video_id)
  1543. # Attempt to extract SWF player URL
  1544. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1545. if mobj is not None:
  1546. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1547. else:
  1548. player_url = None
  1549. dash_mpds = []
  1550. def add_dash_mpd(video_info):
  1551. dash_mpd = video_info.get('dashmpd')
  1552. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1553. dash_mpds.append(dash_mpd[0])
  1554. def add_dash_mpd_pr(pl_response):
  1555. dash_mpd = url_or_none(try_get(
  1556. pl_response, lambda x: x['streamingData']['dashManifestUrl'],
  1557. compat_str))
  1558. if dash_mpd and dash_mpd not in dash_mpds:
  1559. dash_mpds.append(dash_mpd)
  1560. is_live = None
  1561. view_count = None
  1562. def extract_view_count(v_info):
  1563. return int_or_none(try_get(v_info, lambda x: x['view_count'][0]))
  1564. def extract_token(v_info):
  1565. return dict_get(v_info, ('account_playback_token', 'accountPlaybackToken', 'token'))
  1566. player_response = {}
  1567. # Get video info
  1568. embed_webpage = None
  1569. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1570. age_gate = True
  1571. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1572. # this can be viewed without login into Youtube
  1573. url = proto + '://www.youtube.com/embed/%s' % video_id
  1574. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1575. data = compat_urllib_parse_urlencode({
  1576. 'video_id': video_id,
  1577. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1578. 'sts': self._search_regex(
  1579. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1580. })
  1581. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1582. video_info_webpage = self._download_webpage(
  1583. video_info_url, video_id,
  1584. note='Refetching age-gated info webpage',
  1585. errnote='unable to download video info webpage')
  1586. video_info = compat_parse_qs(video_info_webpage)
  1587. add_dash_mpd(video_info)
  1588. else:
  1589. age_gate = False
  1590. video_info = None
  1591. sts = None
  1592. # Try looking directly into the video webpage
  1593. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1594. if ytplayer_config:
  1595. args = ytplayer_config['args']
  1596. if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
  1597. # Convert to the same format returned by compat_parse_qs
  1598. video_info = dict((k, [v]) for k, v in args.items())
  1599. add_dash_mpd(video_info)
  1600. # Rental video is not rented but preview is available (e.g.
  1601. # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
  1602. # https://github.com/ytdl-org/youtube-dl/issues/10532)
  1603. if not video_info and args.get('ypc_vid'):
  1604. return self.url_result(
  1605. args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
  1606. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1607. is_live = True
  1608. sts = ytplayer_config.get('sts')
  1609. if not player_response:
  1610. pl_response = str_or_none(args.get('player_response'))
  1611. if pl_response:
  1612. pl_response = self._parse_json(pl_response, video_id, fatal=False)
  1613. if isinstance(pl_response, dict):
  1614. player_response = pl_response
  1615. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1616. add_dash_mpd_pr(player_response)
  1617. # We also try looking in get_video_info since it may contain different dashmpd
  1618. # URL that points to a DASH manifest with possibly different itag set (some itags
  1619. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1620. # manifest pointed by get_video_info's dashmpd).
  1621. # The general idea is to take a union of itags of both DASH manifests (for example
  1622. # video with such 'manifest behavior' see https://github.com/ytdl-org/youtube-dl/issues/6093)
  1623. self.report_video_info_webpage_download(video_id)
  1624. for el in ('embedded', 'detailpage', 'vevo', ''):
  1625. query = {
  1626. 'video_id': video_id,
  1627. 'ps': 'default',
  1628. 'eurl': '',
  1629. 'gl': 'US',
  1630. 'hl': 'en',
  1631. }
  1632. if el:
  1633. query['el'] = el
  1634. if sts:
  1635. query['sts'] = sts
  1636. video_info_webpage = self._download_webpage(
  1637. '%s://www.youtube.com/get_video_info' % proto,
  1638. video_id, note=False,
  1639. errnote='unable to download video info webpage',
  1640. fatal=False, query=query)
  1641. if not video_info_webpage:
  1642. continue
  1643. get_video_info = compat_parse_qs(video_info_webpage)
  1644. if not player_response:
  1645. pl_response = get_video_info.get('player_response', [None])[0]
  1646. if isinstance(pl_response, dict):
  1647. player_response = pl_response
  1648. add_dash_mpd_pr(player_response)
  1649. add_dash_mpd(get_video_info)
  1650. if view_count is None:
  1651. view_count = extract_view_count(get_video_info)
  1652. if not video_info:
  1653. video_info = get_video_info
  1654. get_token = extract_token(get_video_info)
  1655. if get_token:
  1656. # Different get_video_info requests may report different results, e.g.
  1657. # some may report video unavailability, but some may serve it without
  1658. # any complaint (see https://github.com/ytdl-org/youtube-dl/issues/7362,
  1659. # the original webpage as well as el=info and el=embedded get_video_info
  1660. # requests report video unavailability due to geo restriction while
  1661. # el=detailpage succeeds and returns valid data). This is probably
  1662. # due to YouTube measures against IP ranges of hosting providers.
  1663. # Working around by preferring the first succeeded video_info containing
  1664. # the token if no such video_info yet was found.
  1665. token = extract_token(video_info)
  1666. if not token:
  1667. video_info = get_video_info
  1668. break
  1669. def extract_unavailable_message():
  1670. return self._html_search_regex(
  1671. r'(?s)<h1[^>]+id="unavailable-message"[^>]*>(.+?)</h1>',
  1672. video_webpage, 'unavailable message', default=None)
  1673. if not video_info:
  1674. unavailable_message = extract_unavailable_message()
  1675. if not unavailable_message:
  1676. unavailable_message = 'Unable to extract video data'
  1677. raise ExtractorError(
  1678. 'YouTube said: %s' % unavailable_message, expected=True, video_id=video_id)
  1679. video_details = try_get(
  1680. player_response, lambda x: x['videoDetails'], dict) or {}
  1681. # title
  1682. if 'title' in video_info:
  1683. video_title = video_info['title'][0]
  1684. elif 'title' in player_response:
  1685. video_title = video_details['title']
  1686. else:
  1687. self._downloader.report_warning('Unable to extract video title')
  1688. video_title = '_'
  1689. # description
  1690. description_original = video_description = get_element_by_id("eow-description", video_webpage)
  1691. if video_description:
  1692. def replace_url(m):
  1693. redir_url = compat_urlparse.urljoin(url, m.group(1))
  1694. parsed_redir_url = compat_urllib_parse_urlparse(redir_url)
  1695. if re.search(r'^(?:www\.)?(?:youtube(?:-nocookie)?\.com|youtu\.be)$', parsed_redir_url.netloc) and parsed_redir_url.path == '/redirect':
  1696. qs = compat_parse_qs(parsed_redir_url.query)
  1697. q = qs.get('q')
  1698. if q and q[0]:
  1699. return q[0]
  1700. return redir_url
  1701. description_original = video_description = re.sub(r'''(?x)
  1702. <a\s+
  1703. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1704. (?:title|href)="([^"]+)"\s+
  1705. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1706. class="[^"]*"[^>]*>
  1707. [^<]+\.{3}\s*
  1708. </a>
  1709. ''', replace_url, video_description)
  1710. video_description = clean_html(video_description)
  1711. else:
  1712. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1713. if fd_mobj:
  1714. video_description = unescapeHTML(fd_mobj.group(1))
  1715. else:
  1716. video_description = ''
  1717. if not smuggled_data.get('force_singlefeed', False):
  1718. if not self._downloader.params.get('noplaylist'):
  1719. multifeed_metadata_list = try_get(
  1720. player_response,
  1721. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1722. compat_str) or try_get(
  1723. video_info, lambda x: x['multifeed_metadata_list'][0], compat_str)
  1724. if multifeed_metadata_list:
  1725. entries = []
  1726. feed_ids = []
  1727. for feed in multifeed_metadata_list.split(','):
  1728. # Unquote should take place before split on comma (,) since textual
  1729. # fields may contain comma as well (see
  1730. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1731. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1732. entries.append({
  1733. '_type': 'url_transparent',
  1734. 'ie_key': 'Youtube',
  1735. 'url': smuggle_url(
  1736. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1737. {'force_singlefeed': True}),
  1738. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1739. })
  1740. feed_ids.append(feed_data['id'][0])
  1741. self.to_screen(
  1742. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1743. % (', '.join(feed_ids), video_id))
  1744. return self.playlist_result(entries, video_id, video_title, video_description)
  1745. else:
  1746. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1747. if view_count is None:
  1748. view_count = extract_view_count(video_info)
  1749. if view_count is None and video_details:
  1750. view_count = int_or_none(video_details.get('viewCount'))
  1751. # Check for "rental" videos
  1752. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1753. raise ExtractorError('"rental" videos not supported. See https://github.com/ytdl-org/youtube-dl/issues/359 for more information.', expected=True)
  1754. def _extract_filesize(media_url):
  1755. return int_or_none(self._search_regex(
  1756. r'\bclen[=/](\d+)', media_url, 'filesize', default=None))
  1757. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1758. self.report_rtmp_download()
  1759. formats = [{
  1760. 'format_id': '_rtmp',
  1761. 'protocol': 'rtmp',
  1762. 'url': video_info['conn'][0],
  1763. 'player_url': player_url,
  1764. }]
  1765. 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):
  1766. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1767. if 'rtmpe%3Dyes' in encoded_url_map:
  1768. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/ytdl-org/youtube-dl/issues/343 for more information.', expected=True)
  1769. formats_spec = {}
  1770. fmt_list = video_info.get('fmt_list', [''])[0]
  1771. if fmt_list:
  1772. for fmt in fmt_list.split(','):
  1773. spec = fmt.split('/')
  1774. if len(spec) > 1:
  1775. width_height = spec[1].split('x')
  1776. if len(width_height) == 2:
  1777. formats_spec[spec[0]] = {
  1778. 'resolution': spec[1],
  1779. 'width': int_or_none(width_height[0]),
  1780. 'height': int_or_none(width_height[1]),
  1781. }
  1782. q = qualities(['small', 'medium', 'hd720'])
  1783. streaming_formats = try_get(player_response, lambda x: x['streamingData']['formats'], list)
  1784. if streaming_formats:
  1785. for fmt in streaming_formats:
  1786. itag = str_or_none(fmt.get('itag'))
  1787. if not itag:
  1788. continue
  1789. quality = fmt.get('quality')
  1790. quality_label = fmt.get('qualityLabel') or quality
  1791. formats_spec[itag] = {
  1792. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1793. 'filesize': int_or_none(fmt.get('contentLength')),
  1794. 'format_note': quality_label,
  1795. 'fps': int_or_none(fmt.get('fps')),
  1796. 'height': int_or_none(fmt.get('height')),
  1797. 'quality': q(quality),
  1798. # bitrate for itag 43 is always 2147483647
  1799. 'tbr': float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000) if itag != '43' else None,
  1800. 'width': int_or_none(fmt.get('width')),
  1801. }
  1802. formats = []
  1803. for url_data_str in encoded_url_map.split(','):
  1804. url_data = compat_parse_qs(url_data_str)
  1805. if 'itag' not in url_data or 'url' not in url_data or url_data.get('drm_families'):
  1806. continue
  1807. stream_type = int_or_none(try_get(url_data, lambda x: x['stream_type'][0]))
  1808. # Unsupported FORMAT_STREAM_TYPE_OTF
  1809. if stream_type == 3:
  1810. continue
  1811. format_id = url_data['itag'][0]
  1812. url = url_data['url'][0]
  1813. if 's' in url_data or self._downloader.params.get('youtube_include_dash_manifest', True):
  1814. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1815. jsplayer_url_json = self._search_regex(
  1816. ASSETS_RE,
  1817. embed_webpage if age_gate else video_webpage,
  1818. 'JS player URL (1)', default=None)
  1819. if not jsplayer_url_json and not age_gate:
  1820. # We need the embed website after all
  1821. if embed_webpage is None:
  1822. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1823. embed_webpage = self._download_webpage(
  1824. embed_url, video_id, 'Downloading embed webpage')
  1825. jsplayer_url_json = self._search_regex(
  1826. ASSETS_RE, embed_webpage, 'JS player URL')
  1827. player_url = json.loads(jsplayer_url_json)
  1828. if player_url is None:
  1829. player_url_json = self._search_regex(
  1830. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1831. video_webpage, 'age gate player URL')
  1832. player_url = json.loads(player_url_json)
  1833. if 'sig' in url_data:
  1834. url += '&signature=' + url_data['sig'][0]
  1835. elif 's' in url_data:
  1836. encrypted_sig = url_data['s'][0]
  1837. if self._downloader.params.get('verbose'):
  1838. if player_url is None:
  1839. player_version = 'unknown'
  1840. player_desc = 'unknown'
  1841. else:
  1842. if player_url.endswith('swf'):
  1843. player_version = self._search_regex(
  1844. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1845. 'flash player', fatal=False)
  1846. player_desc = 'flash player %s' % player_version
  1847. else:
  1848. player_version = self._search_regex(
  1849. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js',
  1850. r'(?:www|player(?:_ias)?)-([^/]+)(?:/[a-z]{2,3}_[A-Z]{2})?/base\.js'],
  1851. player_url,
  1852. 'html5 player', fatal=False)
  1853. player_desc = 'html5 player %s' % player_version
  1854. parts_sizes = self._signature_cache_id(encrypted_sig)
  1855. self.to_screen('{%s} signature length %s, %s' %
  1856. (format_id, parts_sizes, player_desc))
  1857. signature = self._decrypt_signature(
  1858. encrypted_sig, video_id, player_url, age_gate)
  1859. sp = try_get(url_data, lambda x: x['sp'][0], compat_str) or 'signature'
  1860. url += '&%s=%s' % (sp, signature)
  1861. if 'ratebypass' not in url:
  1862. url += '&ratebypass=yes'
  1863. dct = {
  1864. 'format_id': format_id,
  1865. 'url': url,
  1866. 'player_url': player_url,
  1867. }
  1868. if format_id in self._formats:
  1869. dct.update(self._formats[format_id])
  1870. if format_id in formats_spec:
  1871. dct.update(formats_spec[format_id])
  1872. # Some itags are not included in DASH manifest thus corresponding formats will
  1873. # lack metadata (see https://github.com/ytdl-org/youtube-dl/pull/5993).
  1874. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1875. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1876. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1877. filesize = int_or_none(url_data.get(
  1878. 'clen', [None])[0]) or _extract_filesize(url)
  1879. quality = url_data.get('quality', [None])[0]
  1880. more_fields = {
  1881. 'filesize': filesize,
  1882. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1883. 'width': width,
  1884. 'height': height,
  1885. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1886. 'format_note': url_data.get('quality_label', [None])[0] or quality,
  1887. 'quality': q(quality),
  1888. }
  1889. for key, value in more_fields.items():
  1890. if value:
  1891. dct[key] = value
  1892. type_ = url_data.get('type', [None])[0]
  1893. if type_:
  1894. type_split = type_.split(';')
  1895. kind_ext = type_split[0].split('/')
  1896. if len(kind_ext) == 2:
  1897. kind, _ = kind_ext
  1898. dct['ext'] = mimetype2ext(type_split[0])
  1899. if kind in ('audio', 'video'):
  1900. codecs = None
  1901. for mobj in re.finditer(
  1902. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1903. if mobj.group('key') == 'codecs':
  1904. codecs = mobj.group('val')
  1905. break
  1906. if codecs:
  1907. dct.update(parse_codecs(codecs))
  1908. if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
  1909. dct['downloader_options'] = {
  1910. # Youtube throttles chunks >~10M
  1911. 'http_chunk_size': 10485760,
  1912. }
  1913. formats.append(dct)
  1914. else:
  1915. manifest_url = (
  1916. url_or_none(try_get(
  1917. player_response,
  1918. lambda x: x['streamingData']['hlsManifestUrl'],
  1919. compat_str))
  1920. or url_or_none(try_get(
  1921. video_info, lambda x: x['hlsvp'][0], compat_str)))
  1922. if manifest_url:
  1923. formats = []
  1924. m3u8_formats = self._extract_m3u8_formats(
  1925. manifest_url, video_id, 'mp4', fatal=False)
  1926. for a_format in m3u8_formats:
  1927. itag = self._search_regex(
  1928. r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
  1929. if itag:
  1930. a_format['format_id'] = itag
  1931. if itag in self._formats:
  1932. dct = self._formats[itag].copy()
  1933. dct.update(a_format)
  1934. a_format = dct
  1935. a_format['player_url'] = player_url
  1936. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1937. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1938. formats.append(a_format)
  1939. else:
  1940. error_message = clean_html(video_info.get('reason', [None])[0])
  1941. if not error_message:
  1942. error_message = extract_unavailable_message()
  1943. if error_message:
  1944. raise ExtractorError(error_message, expected=True)
  1945. raise ExtractorError('no conn, hlsvp, hlsManifestUrl or url_encoded_fmt_stream_map information found in video info')
  1946. # uploader
  1947. video_uploader = try_get(
  1948. video_info, lambda x: x['author'][0],
  1949. compat_str) or str_or_none(video_details.get('author'))
  1950. if video_uploader:
  1951. video_uploader = compat_urllib_parse_unquote_plus(video_uploader)
  1952. else:
  1953. self._downloader.report_warning('unable to extract uploader name')
  1954. # uploader_id
  1955. video_uploader_id = None
  1956. video_uploader_url = None
  1957. mobj = re.search(
  1958. r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  1959. video_webpage)
  1960. if mobj is not None:
  1961. video_uploader_id = mobj.group('uploader_id')
  1962. video_uploader_url = mobj.group('uploader_url')
  1963. else:
  1964. self._downloader.report_warning('unable to extract uploader nickname')
  1965. channel_id = (
  1966. str_or_none(video_details.get('channelId'))
  1967. or self._html_search_meta(
  1968. 'channelId', video_webpage, 'channel id', default=None)
  1969. or self._search_regex(
  1970. r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  1971. video_webpage, 'channel id', default=None, group='id'))
  1972. channel_url = 'http://www.youtube.com/channel/%s' % channel_id if channel_id else None
  1973. # thumbnail image
  1974. # We try first to get a high quality image:
  1975. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1976. video_webpage, re.DOTALL)
  1977. if m_thumb is not None:
  1978. video_thumbnail = m_thumb.group(1)
  1979. elif 'thumbnail_url' not in video_info:
  1980. self._downloader.report_warning('unable to extract video thumbnail')
  1981. video_thumbnail = None
  1982. else: # don't panic if we can't find it
  1983. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  1984. # upload date
  1985. upload_date = self._html_search_meta(
  1986. 'datePublished', video_webpage, 'upload date', default=None)
  1987. if not upload_date:
  1988. upload_date = self._search_regex(
  1989. [r'(?s)id="eow-date.*?>(.*?)</span>',
  1990. r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'],
  1991. video_webpage, 'upload date', default=None)
  1992. upload_date = unified_strdate(upload_date)
  1993. video_license = self._html_search_regex(
  1994. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  1995. video_webpage, 'license', default=None)
  1996. m_music = re.search(
  1997. r'''(?x)
  1998. <h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*
  1999. <ul[^>]*>\s*
  2000. <li>(?P<title>.+?)
  2001. by (?P<creator>.+?)
  2002. (?:
  2003. \(.+?\)|
  2004. <a[^>]*
  2005. (?:
  2006. \bhref=["\']/red[^>]*>| # drop possible
  2007. >\s*Listen ad-free with YouTube Red # YouTube Red ad
  2008. )
  2009. .*?
  2010. )?</li
  2011. ''',
  2012. video_webpage)
  2013. if m_music:
  2014. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  2015. video_creator = clean_html(m_music.group('creator'))
  2016. else:
  2017. video_alt_title = video_creator = None
  2018. def extract_meta(field):
  2019. return self._html_search_regex(
  2020. r'<h4[^>]+class="title"[^>]*>\s*%s\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li>\s*' % field,
  2021. video_webpage, field, default=None)
  2022. track = extract_meta('Song')
  2023. artist = extract_meta('Artist')
  2024. album = extract_meta('Album')
  2025. # Youtube Music Auto-generated description
  2026. release_date = release_year = None
  2027. if video_description:
  2028. 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)
  2029. if mobj:
  2030. if not track:
  2031. track = mobj.group('track').strip()
  2032. if not artist:
  2033. artist = mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·'))
  2034. if not album:
  2035. album = mobj.group('album'.strip())
  2036. release_year = mobj.group('release_year')
  2037. release_date = mobj.group('release_date')
  2038. if release_date:
  2039. release_date = release_date.replace('-', '')
  2040. if not release_year:
  2041. release_year = int(release_date[:4])
  2042. if release_year:
  2043. release_year = int(release_year)
  2044. m_episode = re.search(
  2045. r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
  2046. video_webpage)
  2047. if m_episode:
  2048. series = unescapeHTML(m_episode.group('series'))
  2049. season_number = int(m_episode.group('season'))
  2050. episode_number = int(m_episode.group('episode'))
  2051. else:
  2052. series = season_number = episode_number = None
  2053. m_cat_container = self._search_regex(
  2054. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  2055. video_webpage, 'categories', default=None)
  2056. if m_cat_container:
  2057. category = self._html_search_regex(
  2058. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  2059. default=None)
  2060. video_categories = None if category is None else [category]
  2061. else:
  2062. video_categories = None
  2063. video_tags = [
  2064. unescapeHTML(m.group('content'))
  2065. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  2066. def _extract_count(count_name):
  2067. return str_to_int(self._search_regex(
  2068. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  2069. % re.escape(count_name),
  2070. video_webpage, count_name, default=None))
  2071. like_count = _extract_count('like')
  2072. dislike_count = _extract_count('dislike')
  2073. if view_count is None:
  2074. view_count = str_to_int(self._search_regex(
  2075. r'<[^>]+class=["\']watch-view-count[^>]+>\s*([\d,\s]+)', video_webpage,
  2076. 'view count', default=None))
  2077. average_rating = (
  2078. float_or_none(video_details.get('averageRating'))
  2079. or try_get(video_info, lambda x: float_or_none(x['avg_rating'][0])))
  2080. # subtitles
  2081. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  2082. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  2083. video_duration = try_get(
  2084. video_info, lambda x: int_or_none(x['length_seconds'][0]))
  2085. if not video_duration:
  2086. video_duration = int_or_none(video_details.get('lengthSeconds'))
  2087. if not video_duration:
  2088. video_duration = parse_duration(self._html_search_meta(
  2089. 'duration', video_webpage, 'video duration'))
  2090. # annotations
  2091. video_annotations = None
  2092. if self._downloader.params.get('writeannotations', False):
  2093. video_annotations = self._extract_annotations(video_id)
  2094. chapters = self._extract_chapters(description_original, video_duration)
  2095. # Look for the DASH manifest
  2096. if self._downloader.params.get('youtube_include_dash_manifest', True):
  2097. dash_mpd_fatal = True
  2098. for mpd_url in dash_mpds:
  2099. dash_formats = {}
  2100. try:
  2101. def decrypt_sig(mobj):
  2102. s = mobj.group(1)
  2103. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  2104. return '/signature/%s' % dec_s
  2105. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  2106. for df in self._extract_mpd_formats(
  2107. mpd_url, video_id, fatal=dash_mpd_fatal,
  2108. formats_dict=self._formats):
  2109. if not df.get('filesize'):
  2110. df['filesize'] = _extract_filesize(df['url'])
  2111. # Do not overwrite DASH format found in some previous DASH manifest
  2112. if df['format_id'] not in dash_formats:
  2113. dash_formats[df['format_id']] = df
  2114. # Additional DASH manifests may end up in HTTP Error 403 therefore
  2115. # allow them to fail without bug report message if we already have
  2116. # some DASH manifest succeeded. This is temporary workaround to reduce
  2117. # burst of bug reports until we figure out the reason and whether it
  2118. # can be fixed at all.
  2119. dash_mpd_fatal = False
  2120. except (ExtractorError, KeyError) as e:
  2121. self.report_warning(
  2122. 'Skipping DASH manifest: %r' % e, video_id)
  2123. if dash_formats:
  2124. # Remove the formats we found through non-DASH, they
  2125. # contain less info and it can be wrong, because we use
  2126. # fixed values (for example the resolution). See
  2127. # https://github.com/ytdl-org/youtube-dl/issues/5774 for an
  2128. # example.
  2129. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  2130. formats.extend(dash_formats.values())
  2131. # Check for malformed aspect ratio
  2132. stretched_m = re.search(
  2133. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  2134. video_webpage)
  2135. if stretched_m:
  2136. w = float(stretched_m.group('w'))
  2137. h = float(stretched_m.group('h'))
  2138. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  2139. # We will only process correct ratios.
  2140. if w > 0 and h > 0:
  2141. ratio = w / h
  2142. for f in formats:
  2143. if f.get('vcodec') != 'none':
  2144. f['stretched_ratio'] = ratio
  2145. if not formats:
  2146. token = extract_token(video_info)
  2147. if not token:
  2148. if 'reason' in video_info:
  2149. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  2150. regions_allowed = self._html_search_meta(
  2151. 'regionsAllowed', video_webpage, default=None)
  2152. countries = regions_allowed.split(',') if regions_allowed else None
  2153. self.raise_geo_restricted(
  2154. msg=video_info['reason'][0], countries=countries)
  2155. reason = video_info['reason'][0]
  2156. if 'Invalid parameters' in reason:
  2157. unavailable_message = extract_unavailable_message()
  2158. if unavailable_message:
  2159. reason = unavailable_message
  2160. raise ExtractorError(
  2161. 'YouTube said: %s' % reason,
  2162. expected=True, video_id=video_id)
  2163. else:
  2164. raise ExtractorError(
  2165. '"token" parameter not in video info for unknown reason',
  2166. video_id=video_id)
  2167. if not formats and (video_info.get('license_info') or try_get(player_response, lambda x: x['streamingData']['licenseInfos'])):
  2168. raise ExtractorError('This video is DRM protected.', expected=True)
  2169. self._sort_formats(formats)
  2170. self.mark_watched(video_id, video_info, player_response)
  2171. return {
  2172. 'id': video_id,
  2173. 'uploader': video_uploader,
  2174. 'uploader_id': video_uploader_id,
  2175. 'uploader_url': video_uploader_url,
  2176. 'channel_id': channel_id,
  2177. 'channel_url': channel_url,
  2178. 'upload_date': upload_date,
  2179. 'license': video_license,
  2180. 'creator': video_creator or artist,
  2181. 'title': video_title,
  2182. 'alt_title': video_alt_title or track,
  2183. 'thumbnail': video_thumbnail,
  2184. 'description': video_description,
  2185. 'categories': video_categories,
  2186. 'tags': video_tags,
  2187. 'subtitles': video_subtitles,
  2188. 'automatic_captions': automatic_captions,
  2189. 'duration': video_duration,
  2190. 'age_limit': 18 if age_gate else 0,
  2191. 'annotations': video_annotations,
  2192. 'chapters': chapters,
  2193. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  2194. 'view_count': view_count,
  2195. 'like_count': like_count,
  2196. 'dislike_count': dislike_count,
  2197. 'average_rating': average_rating,
  2198. 'formats': formats,
  2199. 'is_live': is_live,
  2200. 'start_time': start_time,
  2201. 'end_time': end_time,
  2202. 'series': series,
  2203. 'season_number': season_number,
  2204. 'episode_number': episode_number,
  2205. 'track': track,
  2206. 'artist': artist,
  2207. 'album': album,
  2208. 'release_date': release_date,
  2209. 'release_year': release_year,
  2210. }
  2211. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  2212. IE_DESC = 'YouTube.com playlists'
  2213. _VALID_URL = r"""(?x)(?:
  2214. (?:https?://)?
  2215. (?:\w+\.)?
  2216. (?:
  2217. (?:
  2218. youtube\.com|
  2219. invidio\.us
  2220. )
  2221. /
  2222. (?:
  2223. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
  2224. \? (?:.*?[&;])*? (?:p|a|list)=
  2225. | p/
  2226. )|
  2227. youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
  2228. )
  2229. (
  2230. (?:PL|LL|EC|UU|FL|RD|UL|TL|OLAK5uy_)?[0-9A-Za-z-_]{10,}
  2231. # Top tracks, they can also include dots
  2232. |(?:MC)[\w\.]*
  2233. )
  2234. .*
  2235. |
  2236. (%(playlist_id)s)
  2237. )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2238. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  2239. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
  2240. IE_NAME = 'youtube:playlist'
  2241. _TESTS = [{
  2242. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  2243. 'info_dict': {
  2244. 'title': 'ytdl test PL',
  2245. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  2246. },
  2247. 'playlist_count': 3,
  2248. }, {
  2249. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  2250. 'info_dict': {
  2251. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  2252. 'title': 'YDL_Empty_List',
  2253. },
  2254. 'playlist_count': 0,
  2255. 'skip': 'This playlist is private',
  2256. }, {
  2257. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2258. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2259. 'info_dict': {
  2260. 'title': '29C3: Not my department',
  2261. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2262. },
  2263. 'playlist_count': 95,
  2264. }, {
  2265. 'note': 'issue #673',
  2266. 'url': 'PLBB231211A4F62143',
  2267. 'info_dict': {
  2268. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2269. 'id': 'PLBB231211A4F62143',
  2270. },
  2271. 'playlist_mincount': 26,
  2272. }, {
  2273. 'note': 'Large playlist',
  2274. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2275. 'info_dict': {
  2276. 'title': 'Uploads from Cauchemar',
  2277. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2278. },
  2279. 'playlist_mincount': 799,
  2280. }, {
  2281. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2282. 'info_dict': {
  2283. 'title': 'YDL_safe_search',
  2284. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2285. },
  2286. 'playlist_count': 2,
  2287. 'skip': 'This playlist is private',
  2288. }, {
  2289. 'note': 'embedded',
  2290. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2291. 'playlist_count': 4,
  2292. 'info_dict': {
  2293. 'title': 'JODA15',
  2294. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2295. }
  2296. }, {
  2297. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2298. 'playlist_mincount': 485,
  2299. 'info_dict': {
  2300. 'title': '2017 華語最新單曲 (2/24更新)',
  2301. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2302. }
  2303. }, {
  2304. 'note': 'Embedded SWF player',
  2305. 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  2306. 'playlist_count': 4,
  2307. 'info_dict': {
  2308. 'title': 'JODA7',
  2309. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  2310. }
  2311. }, {
  2312. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2313. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2314. 'info_dict': {
  2315. 'title': 'Uploads from Interstellar Movie',
  2316. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2317. },
  2318. 'playlist_mincount': 21,
  2319. }, {
  2320. # Playlist URL that does not actually serve a playlist
  2321. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2322. 'info_dict': {
  2323. 'id': 'FqZTN594JQw',
  2324. 'ext': 'webm',
  2325. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2326. 'uploader': 'STREEM',
  2327. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2328. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2329. 'upload_date': '20150526',
  2330. 'license': 'Standard YouTube License',
  2331. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2332. 'categories': ['People & Blogs'],
  2333. 'tags': list,
  2334. 'view_count': int,
  2335. 'like_count': int,
  2336. 'dislike_count': int,
  2337. },
  2338. 'params': {
  2339. 'skip_download': True,
  2340. },
  2341. 'add_ie': [YoutubeIE.ie_key()],
  2342. }, {
  2343. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2344. 'info_dict': {
  2345. 'id': 'yeWKywCrFtk',
  2346. 'ext': 'mp4',
  2347. 'title': 'Small Scale Baler and Braiding Rugs',
  2348. 'uploader': 'Backus-Page House Museum',
  2349. 'uploader_id': 'backuspagemuseum',
  2350. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2351. 'upload_date': '20161008',
  2352. 'license': 'Standard YouTube License',
  2353. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2354. 'categories': ['Nonprofits & Activism'],
  2355. 'tags': list,
  2356. 'like_count': int,
  2357. 'dislike_count': int,
  2358. },
  2359. 'params': {
  2360. 'noplaylist': True,
  2361. 'skip_download': True,
  2362. },
  2363. }, {
  2364. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  2365. 'only_matching': True,
  2366. }, {
  2367. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2368. 'only_matching': True,
  2369. }, {
  2370. # music album playlist
  2371. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2372. 'only_matching': True,
  2373. }, {
  2374. 'url': 'https://invidio.us/playlist?list=PLDIoUOhQQPlXr63I_vwF9GD8sAKh77dWU',
  2375. 'only_matching': True,
  2376. }]
  2377. def _real_initialize(self):
  2378. self._login()
  2379. def _extract_mix(self, playlist_id):
  2380. # The mixes are generated from a single video
  2381. # the id of the playlist is just 'RD' + video_id
  2382. ids = []
  2383. last_id = playlist_id[-11:]
  2384. for n in itertools.count(1):
  2385. url = 'https://youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
  2386. webpage = self._download_webpage(
  2387. url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
  2388. new_ids = orderedSet(re.findall(
  2389. r'''(?xs)data-video-username=".*?".*?
  2390. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  2391. webpage))
  2392. # Fetch new pages until all the videos are repeated, it seems that
  2393. # there are always 51 unique videos.
  2394. new_ids = [_id for _id in new_ids if _id not in ids]
  2395. if not new_ids:
  2396. break
  2397. ids.extend(new_ids)
  2398. last_id = ids[-1]
  2399. url_results = self._ids_to_results(ids)
  2400. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  2401. title_span = (
  2402. search_title('playlist-title')
  2403. or search_title('title long-title')
  2404. or search_title('title'))
  2405. title = clean_html(title_span)
  2406. return self.playlist_result(url_results, playlist_id, title)
  2407. def _extract_playlist(self, playlist_id):
  2408. url = self._TEMPLATE_URL % playlist_id
  2409. page = self._download_webpage(url, playlist_id)
  2410. # the yt-alert-message now has tabindex attribute (see https://github.com/ytdl-org/youtube-dl/issues/11604)
  2411. for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
  2412. match = match.strip()
  2413. # Check if the playlist exists or is private
  2414. mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
  2415. if mobj:
  2416. reason = mobj.group('reason')
  2417. message = 'This playlist %s' % reason
  2418. if 'private' in reason:
  2419. message += ', use --username or --netrc to access it'
  2420. message += '.'
  2421. raise ExtractorError(message, expected=True)
  2422. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  2423. raise ExtractorError(
  2424. 'Invalid parameters. Maybe URL is incorrect.',
  2425. expected=True)
  2426. elif re.match(r'[^<]*Choose your language[^<]*', match):
  2427. continue
  2428. else:
  2429. self.report_warning('Youtube gives an alert message: ' + match)
  2430. playlist_title = self._html_search_regex(
  2431. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  2432. page, 'title', default=None)
  2433. _UPLOADER_BASE = r'class=["\']pl-header-details[^>]+>\s*<li>\s*<a[^>]+\bhref='
  2434. uploader = self._search_regex(
  2435. r'%s["\']/(?:user|channel)/[^>]+>([^<]+)' % _UPLOADER_BASE,
  2436. page, 'uploader', default=None)
  2437. mobj = re.search(
  2438. r'%s(["\'])(?P<path>/(?:user|channel)/(?P<uploader_id>.+?))\1' % _UPLOADER_BASE,
  2439. page)
  2440. if mobj:
  2441. uploader_id = mobj.group('uploader_id')
  2442. uploader_url = compat_urlparse.urljoin(url, mobj.group('path'))
  2443. else:
  2444. uploader_id = uploader_url = None
  2445. has_videos = True
  2446. if not playlist_title:
  2447. try:
  2448. # Some playlist URLs don't actually serve a playlist (e.g.
  2449. # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
  2450. next(self._entries(page, playlist_id))
  2451. except StopIteration:
  2452. has_videos = False
  2453. playlist = self.playlist_result(
  2454. self._entries(page, playlist_id), playlist_id, playlist_title)
  2455. playlist.update({
  2456. 'uploader': uploader,
  2457. 'uploader_id': uploader_id,
  2458. 'uploader_url': uploader_url,
  2459. })
  2460. return has_videos, playlist
  2461. def _check_download_just_video(self, url, playlist_id):
  2462. # Check if it's a video-specific URL
  2463. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  2464. video_id = query_dict.get('v', [None])[0] or self._search_regex(
  2465. r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
  2466. 'video id', default=None)
  2467. if video_id:
  2468. if self._downloader.params.get('noplaylist'):
  2469. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2470. return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
  2471. else:
  2472. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2473. return video_id, None
  2474. return None, None
  2475. def _real_extract(self, url):
  2476. # Extract playlist id
  2477. mobj = re.match(self._VALID_URL, url)
  2478. if mobj is None:
  2479. raise ExtractorError('Invalid URL: %s' % url)
  2480. playlist_id = mobj.group(1) or mobj.group(2)
  2481. video_id, video = self._check_download_just_video(url, playlist_id)
  2482. if video:
  2483. return video
  2484. if playlist_id.startswith(('RD', 'UL', 'PU')):
  2485. # Mixes require a custom extraction process
  2486. return self._extract_mix(playlist_id)
  2487. has_videos, playlist = self._extract_playlist(playlist_id)
  2488. if has_videos or not video_id:
  2489. return playlist
  2490. # Some playlist URLs don't actually serve a playlist (see
  2491. # https://github.com/ytdl-org/youtube-dl/issues/10537).
  2492. # Fallback to plain video extraction if there is a video id
  2493. # along with playlist id.
  2494. return self.url_result(video_id, 'Youtube', video_id=video_id)
  2495. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  2496. IE_DESC = 'YouTube.com channels'
  2497. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com|(?:www\.)?invidio\.us)/channel/(?P<id>[0-9A-Za-z_-]+)'
  2498. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  2499. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  2500. IE_NAME = 'youtube:channel'
  2501. _TESTS = [{
  2502. 'note': 'paginated channel',
  2503. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  2504. 'playlist_mincount': 91,
  2505. 'info_dict': {
  2506. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  2507. 'title': 'Uploads from lex will',
  2508. }
  2509. }, {
  2510. 'note': 'Age restricted channel',
  2511. # from https://www.youtube.com/user/DeusExOfficial
  2512. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  2513. 'playlist_mincount': 64,
  2514. 'info_dict': {
  2515. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  2516. 'title': 'Uploads from Deus Ex',
  2517. },
  2518. }, {
  2519. 'url': 'https://invidio.us/channel/UC23qupoDRn9YOAVzeoxjOQA',
  2520. 'only_matching': True,
  2521. }]
  2522. @classmethod
  2523. def suitable(cls, url):
  2524. return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
  2525. else super(YoutubeChannelIE, cls).suitable(url))
  2526. def _build_template_url(self, url, channel_id):
  2527. return self._TEMPLATE_URL % channel_id
  2528. def _real_extract(self, url):
  2529. channel_id = self._match_id(url)
  2530. url = self._build_template_url(url, channel_id)
  2531. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  2532. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  2533. # otherwise fallback on channel by page extraction
  2534. channel_page = self._download_webpage(
  2535. url + '?view=57', channel_id,
  2536. 'Downloading channel page', fatal=False)
  2537. if channel_page is False:
  2538. channel_playlist_id = False
  2539. else:
  2540. channel_playlist_id = self._html_search_meta(
  2541. 'channelId', channel_page, 'channel id', default=None)
  2542. if not channel_playlist_id:
  2543. channel_url = self._html_search_meta(
  2544. ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
  2545. channel_page, 'channel url', default=None)
  2546. if channel_url:
  2547. channel_playlist_id = self._search_regex(
  2548. r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
  2549. channel_url, 'channel id', default=None)
  2550. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  2551. playlist_id = 'UU' + channel_playlist_id[2:]
  2552. return self.url_result(
  2553. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  2554. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  2555. autogenerated = re.search(r'''(?x)
  2556. class="[^"]*?(?:
  2557. channel-header-autogenerated-label|
  2558. yt-channel-title-autogenerated
  2559. )[^"]*"''', channel_page) is not None
  2560. if autogenerated:
  2561. # The videos are contained in a single page
  2562. # the ajax pages can't be used, they are empty
  2563. entries = [
  2564. self.url_result(
  2565. video_id, 'Youtube', video_id=video_id,
  2566. video_title=video_title)
  2567. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  2568. return self.playlist_result(entries, channel_id)
  2569. try:
  2570. next(self._entries(channel_page, channel_id))
  2571. except StopIteration:
  2572. alert_message = self._html_search_regex(
  2573. r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
  2574. channel_page, 'alert', default=None, group='alert')
  2575. if alert_message:
  2576. raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
  2577. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  2578. class YoutubeUserIE(YoutubeChannelIE):
  2579. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  2580. _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_-]+)'
  2581. _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
  2582. IE_NAME = 'youtube:user'
  2583. _TESTS = [{
  2584. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  2585. 'playlist_mincount': 320,
  2586. 'info_dict': {
  2587. 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
  2588. 'title': 'Uploads from The Linux Foundation',
  2589. }
  2590. }, {
  2591. # Only available via https://www.youtube.com/c/12minuteathlete/videos
  2592. # but not https://www.youtube.com/user/12minuteathlete/videos
  2593. 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
  2594. 'playlist_mincount': 249,
  2595. 'info_dict': {
  2596. 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
  2597. 'title': 'Uploads from 12 Minute Athlete',
  2598. }
  2599. }, {
  2600. 'url': 'ytuser:phihag',
  2601. 'only_matching': True,
  2602. }, {
  2603. 'url': 'https://www.youtube.com/c/gametrailers',
  2604. 'only_matching': True,
  2605. }, {
  2606. 'url': 'https://www.youtube.com/gametrailers',
  2607. 'only_matching': True,
  2608. }, {
  2609. # This channel is not available, geo restricted to JP
  2610. 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
  2611. 'only_matching': True,
  2612. }]
  2613. @classmethod
  2614. def suitable(cls, url):
  2615. # Don't return True if the url can be extracted with other youtube
  2616. # extractor, the regex would is too permissive and it would match.
  2617. other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
  2618. if any(ie.suitable(url) for ie in other_yt_ies):
  2619. return False
  2620. else:
  2621. return super(YoutubeUserIE, cls).suitable(url)
  2622. def _build_template_url(self, url, channel_id):
  2623. mobj = re.match(self._VALID_URL, url)
  2624. return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
  2625. class YoutubeLiveIE(YoutubeBaseInfoExtractor):
  2626. IE_DESC = 'YouTube.com live streams'
  2627. _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
  2628. IE_NAME = 'youtube:live'
  2629. _TESTS = [{
  2630. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2631. 'info_dict': {
  2632. 'id': 'a48o2S1cPoo',
  2633. 'ext': 'mp4',
  2634. 'title': 'The Young Turks - Live Main Show',
  2635. 'uploader': 'The Young Turks',
  2636. 'uploader_id': 'TheYoungTurks',
  2637. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2638. 'upload_date': '20150715',
  2639. 'license': 'Standard YouTube License',
  2640. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2641. 'categories': ['News & Politics'],
  2642. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2643. 'like_count': int,
  2644. 'dislike_count': int,
  2645. },
  2646. 'params': {
  2647. 'skip_download': True,
  2648. },
  2649. }, {
  2650. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2651. 'only_matching': True,
  2652. }, {
  2653. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2654. 'only_matching': True,
  2655. }, {
  2656. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2657. 'only_matching': True,
  2658. }]
  2659. def _real_extract(self, url):
  2660. mobj = re.match(self._VALID_URL, url)
  2661. channel_id = mobj.group('id')
  2662. base_url = mobj.group('base_url')
  2663. webpage = self._download_webpage(url, channel_id, fatal=False)
  2664. if webpage:
  2665. page_type = self._og_search_property(
  2666. 'type', webpage, 'page type', default='')
  2667. video_id = self._html_search_meta(
  2668. 'videoId', webpage, 'video id', default=None)
  2669. if page_type.startswith('video') and video_id and re.match(
  2670. r'^[0-9A-Za-z_-]{11}$', video_id):
  2671. return self.url_result(video_id, YoutubeIE.ie_key())
  2672. return self.url_result(base_url)
  2673. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  2674. IE_DESC = 'YouTube.com user/channel playlists'
  2675. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  2676. IE_NAME = 'youtube:playlists'
  2677. _TESTS = [{
  2678. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2679. 'playlist_mincount': 4,
  2680. 'info_dict': {
  2681. 'id': 'ThirstForScience',
  2682. 'title': 'Thirst for Science',
  2683. },
  2684. }, {
  2685. # with "Load more" button
  2686. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2687. 'playlist_mincount': 70,
  2688. 'info_dict': {
  2689. 'id': 'igorkle1',
  2690. 'title': 'Игорь Клейнер',
  2691. },
  2692. }, {
  2693. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  2694. 'playlist_mincount': 17,
  2695. 'info_dict': {
  2696. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  2697. 'title': 'Chem Player',
  2698. },
  2699. }]
  2700. class YoutubeSearchBaseInfoExtractor(YoutubePlaylistBaseInfoExtractor):
  2701. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
  2702. class YoutubeSearchIE(SearchInfoExtractor, YoutubeSearchBaseInfoExtractor):
  2703. IE_DESC = 'YouTube.com searches'
  2704. # there doesn't appear to be a real limit, for example if you search for
  2705. # 'python' you get more than 8.000.000 results
  2706. _MAX_RESULTS = float('inf')
  2707. IE_NAME = 'youtube:search'
  2708. _SEARCH_KEY = 'ytsearch'
  2709. _EXTRA_QUERY_ARGS = {}
  2710. _TESTS = []
  2711. def _get_n_results(self, query, n):
  2712. """Get a specified number of results for a query"""
  2713. videos = []
  2714. limit = n
  2715. url_query = {
  2716. 'search_query': query.encode('utf-8'),
  2717. }
  2718. url_query.update(self._EXTRA_QUERY_ARGS)
  2719. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse_urlencode(url_query)
  2720. for pagenum in itertools.count(1):
  2721. data = self._download_json(
  2722. result_url, video_id='query "%s"' % query,
  2723. note='Downloading page %s' % pagenum,
  2724. errnote='Unable to download API page',
  2725. query={'spf': 'navigate'})
  2726. html_content = data[1]['body']['content']
  2727. if 'class="search-message' in html_content:
  2728. raise ExtractorError(
  2729. '[youtube] No video results', expected=True)
  2730. new_videos = list(self._process_page(html_content))
  2731. videos += new_videos
  2732. if not new_videos or len(videos) > limit:
  2733. break
  2734. next_link = self._html_search_regex(
  2735. r'href="(/results\?[^"]*\bsp=[^"]+)"[^>]*>\s*<span[^>]+class="[^"]*\byt-uix-button-content\b[^"]*"[^>]*>Next',
  2736. html_content, 'next link', default=None)
  2737. if next_link is None:
  2738. break
  2739. result_url = compat_urlparse.urljoin('https://www.youtube.com/', next_link)
  2740. if len(videos) > n:
  2741. videos = videos[:n]
  2742. return self.playlist_result(videos, query)
  2743. class YoutubeSearchDateIE(YoutubeSearchIE):
  2744. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  2745. _SEARCH_KEY = 'ytsearchdate'
  2746. IE_DESC = 'YouTube.com searches, newest videos first'
  2747. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  2748. class YoutubeSearchURLIE(YoutubeSearchBaseInfoExtractor):
  2749. IE_DESC = 'YouTube.com search URLs'
  2750. IE_NAME = 'youtube:search_url'
  2751. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  2752. _TESTS = [{
  2753. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  2754. 'playlist_mincount': 5,
  2755. 'info_dict': {
  2756. 'title': 'youtube-dl test video',
  2757. }
  2758. }, {
  2759. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  2760. 'only_matching': True,
  2761. }]
  2762. def _real_extract(self, url):
  2763. mobj = re.match(self._VALID_URL, url)
  2764. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  2765. webpage = self._download_webpage(url, query)
  2766. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  2767. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  2768. IE_DESC = 'YouTube.com (multi-season) shows'
  2769. _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
  2770. IE_NAME = 'youtube:show'
  2771. _TESTS = [{
  2772. 'url': 'https://www.youtube.com/show/airdisasters',
  2773. 'playlist_mincount': 5,
  2774. 'info_dict': {
  2775. 'id': 'airdisasters',
  2776. 'title': 'Air Disasters',
  2777. }
  2778. }]
  2779. def _real_extract(self, url):
  2780. playlist_id = self._match_id(url)
  2781. return super(YoutubeShowIE, self)._real_extract(
  2782. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  2783. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  2784. """
  2785. Base class for feed extractors
  2786. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  2787. """
  2788. _LOGIN_REQUIRED = True
  2789. @property
  2790. def IE_NAME(self):
  2791. return 'youtube:%s' % self._FEED_NAME
  2792. def _real_initialize(self):
  2793. self._login()
  2794. def _entries(self, page):
  2795. # The extraction process is the same as for playlists, but the regex
  2796. # for the video ids doesn't contain an index
  2797. ids = []
  2798. more_widget_html = content_html = page
  2799. for page_num in itertools.count(1):
  2800. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  2801. # 'recommended' feed has infinite 'load more' and each new portion spins
  2802. # the same videos in (sometimes) slightly different order, so we'll check
  2803. # for unicity and break when portion has no new videos
  2804. new_ids = list(filter(lambda video_id: video_id not in ids, orderedSet(matches)))
  2805. if not new_ids:
  2806. break
  2807. ids.extend(new_ids)
  2808. for entry in self._ids_to_results(new_ids):
  2809. yield entry
  2810. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  2811. if not mobj:
  2812. break
  2813. more = self._download_json(
  2814. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  2815. 'Downloading page #%s' % page_num,
  2816. transform_source=uppercase_escape)
  2817. content_html = more['content_html']
  2818. more_widget_html = more['load_more_widget_html']
  2819. def _real_extract(self, url):
  2820. page = self._download_webpage(
  2821. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  2822. self._PLAYLIST_TITLE)
  2823. return self.playlist_result(
  2824. self._entries(page), playlist_title=self._PLAYLIST_TITLE)
  2825. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  2826. IE_NAME = 'youtube:watchlater'
  2827. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  2828. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  2829. _TESTS = [{
  2830. 'url': 'https://www.youtube.com/playlist?list=WL',
  2831. 'only_matching': True,
  2832. }, {
  2833. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  2834. 'only_matching': True,
  2835. }]
  2836. def _real_extract(self, url):
  2837. _, video = self._check_download_just_video(url, 'WL')
  2838. if video:
  2839. return video
  2840. _, playlist = self._extract_playlist('WL')
  2841. return playlist
  2842. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2843. IE_NAME = 'youtube:favorites'
  2844. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2845. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2846. _LOGIN_REQUIRED = True
  2847. def _real_extract(self, url):
  2848. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  2849. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  2850. return self.url_result(playlist_id, 'YoutubePlaylist')
  2851. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2852. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2853. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  2854. _FEED_NAME = 'recommended'
  2855. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  2856. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2857. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2858. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  2859. _FEED_NAME = 'subscriptions'
  2860. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  2861. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2862. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2863. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
  2864. _FEED_NAME = 'history'
  2865. _PLAYLIST_TITLE = 'Youtube History'
  2866. class YoutubeTruncatedURLIE(InfoExtractor):
  2867. IE_NAME = 'youtube:truncated_url'
  2868. IE_DESC = False # Do not list
  2869. _VALID_URL = r'''(?x)
  2870. (?:https?://)?
  2871. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  2872. (?:watch\?(?:
  2873. feature=[a-z_]+|
  2874. annotation_id=annotation_[^&]+|
  2875. x-yt-cl=[0-9]+|
  2876. hl=[^&]*|
  2877. t=[0-9]+
  2878. )?
  2879. |
  2880. attribution_link\?a=[^&]+
  2881. )
  2882. $
  2883. '''
  2884. _TESTS = [{
  2885. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  2886. 'only_matching': True,
  2887. }, {
  2888. 'url': 'https://www.youtube.com/watch?',
  2889. 'only_matching': True,
  2890. }, {
  2891. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  2892. 'only_matching': True,
  2893. }, {
  2894. 'url': 'https://www.youtube.com/watch?feature=foo',
  2895. 'only_matching': True,
  2896. }, {
  2897. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  2898. 'only_matching': True,
  2899. }, {
  2900. 'url': 'https://www.youtube.com/watch?t=2372',
  2901. 'only_matching': True,
  2902. }]
  2903. def _real_extract(self, url):
  2904. raise ExtractorError(
  2905. 'Did you forget to quote the URL? Remember that & is a meta '
  2906. 'character in most shells, so you want to put the URL in quotes, '
  2907. 'like youtube-dl '
  2908. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  2909. ' or simply youtube-dl BaW_jenozKc .',
  2910. expected=True)
  2911. class YoutubeTruncatedIDIE(InfoExtractor):
  2912. IE_NAME = 'youtube:truncated_id'
  2913. IE_DESC = False # Do not list
  2914. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  2915. _TESTS = [{
  2916. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  2917. 'only_matching': True,
  2918. }]
  2919. def _real_extract(self, url):
  2920. video_id = self._match_id(url)
  2921. raise ExtractorError(
  2922. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  2923. expected=True)