youtube.py 149 KB

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