youtube.py 129 KB

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