youtube.py 128 KB

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