youtube.py 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430
  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 traceback
  9. from .common import InfoExtractor, SearchInfoExtractor
  10. from ..compat import (
  11. compat_chr,
  12. compat_HTTPError,
  13. compat_map as map,
  14. compat_parse_qs,
  15. compat_str,
  16. compat_urllib_parse_unquote_plus,
  17. compat_urllib_parse_urlencode,
  18. compat_urllib_parse_urlparse,
  19. compat_urlparse,
  20. )
  21. from ..jsinterp import JSInterpreter
  22. from ..utils import (
  23. ExtractorError,
  24. clean_html,
  25. dict_get,
  26. error_to_compat_str,
  27. float_or_none,
  28. int_or_none,
  29. js_to_json,
  30. mimetype2ext,
  31. parse_codecs,
  32. parse_duration,
  33. qualities,
  34. remove_start,
  35. smuggle_url,
  36. str_or_none,
  37. str_to_int,
  38. try_get,
  39. unescapeHTML,
  40. unified_strdate,
  41. unsmuggle_url,
  42. update_url_query,
  43. url_or_none,
  44. urlencode_postdata,
  45. urljoin,
  46. )
  47. def parse_qs(url):
  48. return compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  49. class YoutubeBaseInfoExtractor(InfoExtractor):
  50. """Provide base functions for Youtube extractors"""
  51. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  52. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  53. _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
  54. _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
  55. _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
  56. _NETRC_MACHINE = 'youtube'
  57. # If True it will raise an error if no login info is provided
  58. _LOGIN_REQUIRED = False
  59. _PLAYLIST_ID_RE = r'(?:(?:PL|LL|EC|UU|FL|RD|UL|TL|PU|OLAK5uy_)[0-9A-Za-z-_]{10,}|RDMM)'
  60. def _login(self):
  61. """
  62. Attempt to log in to YouTube.
  63. True is returned if successful or skipped.
  64. False is returned if login failed.
  65. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  66. """
  67. username, password = self._get_login_info()
  68. # No authentication to be performed
  69. if username is None:
  70. if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
  71. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  72. return True
  73. login_page = self._download_webpage(
  74. self._LOGIN_URL, None,
  75. note='Downloading login page',
  76. errnote='unable to fetch login page', fatal=False)
  77. if login_page is False:
  78. return
  79. login_form = self._hidden_inputs(login_page)
  80. def req(url, f_req, note, errnote):
  81. data = login_form.copy()
  82. data.update({
  83. 'pstMsg': 1,
  84. 'checkConnection': 'youtube',
  85. 'checkedDomains': 'youtube',
  86. 'hl': 'en',
  87. 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
  88. 'f.req': json.dumps(f_req),
  89. 'flowName': 'GlifWebSignIn',
  90. 'flowEntry': 'ServiceLogin',
  91. # TODO: reverse actual botguard identifier generation algo
  92. 'bgRequest': '["identifier",""]',
  93. })
  94. return self._download_json(
  95. url, None, note=note, errnote=errnote,
  96. transform_source=lambda s: re.sub(r'^[^[]*', '', s),
  97. fatal=False,
  98. data=urlencode_postdata(data), headers={
  99. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  100. 'Google-Accounts-XSRF': 1,
  101. })
  102. def warn(message):
  103. self._downloader.report_warning(message)
  104. lookup_req = [
  105. username,
  106. None, [], None, 'US', None, None, 2, False, True,
  107. [
  108. None, None,
  109. [2, 1, None, 1,
  110. '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',
  111. None, [], 4],
  112. 1, [None, None, []], None, None, None, True
  113. ],
  114. username,
  115. ]
  116. lookup_results = req(
  117. self._LOOKUP_URL, lookup_req,
  118. 'Looking up account info', 'Unable to look up account info')
  119. if lookup_results is False:
  120. return False
  121. user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
  122. if not user_hash:
  123. warn('Unable to extract user hash')
  124. return False
  125. challenge_req = [
  126. user_hash,
  127. None, 1, None, [1, None, None, None, [password, None, True]],
  128. [
  129. 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],
  130. 1, [None, None, []], None, None, None, True
  131. ]]
  132. challenge_results = req(
  133. self._CHALLENGE_URL, challenge_req,
  134. 'Logging in', 'Unable to log in')
  135. if challenge_results is False:
  136. return
  137. login_res = try_get(challenge_results, lambda x: x[0][5], list)
  138. if login_res:
  139. login_msg = try_get(login_res, lambda x: x[5], compat_str)
  140. warn(
  141. 'Unable to login: %s' % 'Invalid password'
  142. if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
  143. return False
  144. res = try_get(challenge_results, lambda x: x[0][-1], list)
  145. if not res:
  146. warn('Unable to extract result entry')
  147. return False
  148. login_challenge = try_get(res, lambda x: x[0][0], list)
  149. if login_challenge:
  150. challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
  151. if challenge_str == 'TWO_STEP_VERIFICATION':
  152. # SEND_SUCCESS - TFA code has been successfully sent to phone
  153. # QUOTA_EXCEEDED - reached the limit of TFA codes
  154. status = try_get(login_challenge, lambda x: x[5], compat_str)
  155. if status == 'QUOTA_EXCEEDED':
  156. warn('Exceeded the limit of TFA codes, try later')
  157. return False
  158. tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
  159. if not tl:
  160. warn('Unable to extract TL')
  161. return False
  162. tfa_code = self._get_tfa_info('2-step verification code')
  163. if not tfa_code:
  164. warn(
  165. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  166. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  167. return False
  168. tfa_code = remove_start(tfa_code, 'G-')
  169. tfa_req = [
  170. user_hash, None, 2, None,
  171. [
  172. 9, None, None, None, None, None, None, None,
  173. [None, tfa_code, True, 2]
  174. ]]
  175. tfa_results = req(
  176. self._TFA_URL.format(tl), tfa_req,
  177. 'Submitting TFA code', 'Unable to submit TFA code')
  178. if tfa_results is False:
  179. return False
  180. tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
  181. if tfa_res:
  182. tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
  183. warn(
  184. 'Unable to finish TFA: %s' % 'Invalid TFA code'
  185. if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
  186. return False
  187. check_cookie_url = try_get(
  188. tfa_results, lambda x: x[0][-1][2], compat_str)
  189. else:
  190. CHALLENGES = {
  191. 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
  192. 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
  193. 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
  194. }
  195. challenge = CHALLENGES.get(
  196. challenge_str,
  197. '%s returned error %s.' % (self.IE_NAME, challenge_str))
  198. warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
  199. return False
  200. else:
  201. check_cookie_url = try_get(res, lambda x: x[2], compat_str)
  202. if not check_cookie_url:
  203. warn('Unable to extract CheckCookie URL')
  204. return False
  205. check_cookie_results = self._download_webpage(
  206. check_cookie_url, None, 'Checking cookie', fatal=False)
  207. if check_cookie_results is False:
  208. return False
  209. if 'https://myaccount.google.com/' not in check_cookie_results:
  210. warn('Unable to log in')
  211. return False
  212. return True
  213. def _initialize_consent(self):
  214. cookies = self._get_cookies('https://www.youtube.com/')
  215. if cookies.get('__Secure-3PSID'):
  216. return
  217. consent_id = None
  218. consent = cookies.get('CONSENT')
  219. if consent:
  220. if 'YES' in consent.value:
  221. return
  222. consent_id = self._search_regex(
  223. r'PENDING\+(\d+)', consent.value, 'consent', default=None)
  224. if not consent_id:
  225. consent_id = random.randint(100, 999)
  226. self._set_cookie('.youtube.com', 'CONSENT', 'YES+cb.20210328-17-p0.en+FX+%s' % consent_id)
  227. def _real_initialize(self):
  228. self._initialize_consent()
  229. if self._downloader is None:
  230. return
  231. if not self._login():
  232. return
  233. _DEFAULT_API_DATA = {
  234. 'context': {
  235. 'client': {
  236. 'clientName': 'WEB',
  237. 'clientVersion': '2.20201021.03.00',
  238. }
  239. },
  240. }
  241. _YT_INITIAL_DATA_RE = r'(?:window\s*\[\s*["\']ytInitialData["\']\s*\]|ytInitialData)\s*=\s*({.+?})\s*;'
  242. _YT_INITIAL_PLAYER_RESPONSE_RE = r'ytInitialPlayerResponse\s*=\s*({.+?})\s*;'
  243. _YT_INITIAL_BOUNDARY_RE = r'(?:var\s+meta|</script|\n)'
  244. def _call_api(self, ep, query, video_id, fatal=True):
  245. data = self._DEFAULT_API_DATA.copy()
  246. data.update(query)
  247. return self._download_json(
  248. 'https://www.youtube.com/youtubei/v1/%s' % ep, video_id=video_id,
  249. note='Downloading API JSON', errnote='Unable to download API page',
  250. data=json.dumps(data).encode('utf8'), fatal=fatal,
  251. headers={'content-type': 'application/json'},
  252. query={'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'})
  253. def _extract_yt_initial_data(self, video_id, webpage):
  254. return self._parse_json(
  255. self._search_regex(
  256. (r'%s\s*%s' % (self._YT_INITIAL_DATA_RE, self._YT_INITIAL_BOUNDARY_RE),
  257. self._YT_INITIAL_DATA_RE), webpage, 'yt initial data'),
  258. video_id)
  259. def _extract_ytcfg(self, video_id, webpage):
  260. return self._parse_json(
  261. self._search_regex(
  262. r'ytcfg\.set\s*\(\s*({.+?})\s*\)\s*;', webpage, 'ytcfg',
  263. default='{}'), video_id, fatal=False) or {}
  264. def _extract_video(self, renderer):
  265. video_id = renderer['videoId']
  266. title = try_get(
  267. renderer,
  268. (lambda x: x['title']['runs'][0]['text'],
  269. lambda x: x['title']['simpleText'],
  270. lambda x: x['headline']['simpleText']), compat_str)
  271. description = try_get(
  272. renderer, lambda x: x['descriptionSnippet']['runs'][0]['text'],
  273. compat_str)
  274. duration = parse_duration(try_get(
  275. renderer, lambda x: x['lengthText']['simpleText'], compat_str))
  276. view_count_text = try_get(
  277. renderer, lambda x: x['viewCountText']['simpleText'], compat_str) or ''
  278. view_count = str_to_int(self._search_regex(
  279. r'^([\d,]+)', re.sub(r'\s', '', view_count_text),
  280. 'view count', default=None))
  281. uploader = try_get(
  282. renderer,
  283. (lambda x: x['ownerText']['runs'][0]['text'],
  284. lambda x: x['shortBylineText']['runs'][0]['text']), compat_str)
  285. return {
  286. '_type': 'url',
  287. 'ie_key': YoutubeIE.ie_key(),
  288. 'id': video_id,
  289. 'url': video_id,
  290. 'title': title,
  291. 'description': description,
  292. 'duration': duration,
  293. 'view_count': view_count,
  294. 'uploader': uploader,
  295. }
  296. def _search_results(self, query, params):
  297. data = {
  298. 'context': {
  299. 'client': {
  300. 'clientName': 'WEB',
  301. 'clientVersion': '2.20201021.03.00',
  302. }
  303. },
  304. 'query': query,
  305. }
  306. if params:
  307. data['params'] = params
  308. for page_num in itertools.count(1):
  309. search = self._download_json(
  310. 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  311. video_id='query "%s"' % query,
  312. note='Downloading page %s' % page_num,
  313. errnote='Unable to download API page', fatal=False,
  314. data=json.dumps(data).encode('utf8'),
  315. headers={'content-type': 'application/json'})
  316. if not search:
  317. break
  318. slr_contents = try_get(
  319. search,
  320. (lambda x: x['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'],
  321. lambda x: x['onResponseReceivedCommands'][0]['appendContinuationItemsAction']['continuationItems']),
  322. list)
  323. if not slr_contents:
  324. break
  325. for slr_content in slr_contents:
  326. isr_contents = try_get(
  327. slr_content,
  328. lambda x: x['itemSectionRenderer']['contents'],
  329. list)
  330. if not isr_contents:
  331. continue
  332. for content in isr_contents:
  333. if not isinstance(content, dict):
  334. continue
  335. video = content.get('videoRenderer')
  336. if not isinstance(video, dict):
  337. continue
  338. video_id = video.get('videoId')
  339. if not video_id:
  340. continue
  341. yield self._extract_video(video)
  342. token = try_get(
  343. slr_contents,
  344. lambda x: x[-1]['continuationItemRenderer']['continuationEndpoint']['continuationCommand']['token'],
  345. compat_str)
  346. if not token:
  347. break
  348. data['continuation'] = token
  349. class YoutubeIE(YoutubeBaseInfoExtractor):
  350. IE_DESC = 'YouTube.com'
  351. _INVIDIOUS_SITES = (
  352. # invidious-redirect websites
  353. r'(?:www\.)?redirect\.invidious\.io',
  354. r'(?:(?:www|dev)\.)?invidio\.us',
  355. # Invidious instances taken from https://github.com/iv-org/documentation/blob/master/Invidious-Instances.md
  356. r'(?:(?:www|no)\.)?invidiou\.sh',
  357. r'(?:(?:www|fi)\.)?invidious\.snopyta\.org',
  358. r'(?:www\.)?invidious\.kabi\.tk',
  359. r'(?:www\.)?invidious\.13ad\.de',
  360. r'(?:www\.)?invidious\.mastodon\.host',
  361. r'(?:www\.)?invidious\.zapashcanon\.fr',
  362. r'(?:www\.)?(?:invidious(?:-us)?|piped)\.kavin\.rocks',
  363. r'(?:www\.)?invidious\.tinfoil-hat\.net',
  364. r'(?:www\.)?invidious\.himiko\.cloud',
  365. r'(?:www\.)?invidious\.reallyancient\.tech',
  366. r'(?:www\.)?invidious\.tube',
  367. r'(?:www\.)?invidiou\.site',
  368. r'(?:www\.)?invidious\.site',
  369. r'(?:www\.)?invidious\.xyz',
  370. r'(?:www\.)?invidious\.nixnet\.xyz',
  371. r'(?:www\.)?invidious\.048596\.xyz',
  372. r'(?:www\.)?invidious\.drycat\.fr',
  373. r'(?:www\.)?inv\.skyn3t\.in',
  374. r'(?:www\.)?tube\.poal\.co',
  375. r'(?:www\.)?tube\.connect\.cafe',
  376. r'(?:www\.)?vid\.wxzm\.sx',
  377. r'(?:www\.)?vid\.mint\.lgbt',
  378. r'(?:www\.)?vid\.puffyan\.us',
  379. r'(?:www\.)?yewtu\.be',
  380. r'(?:www\.)?yt\.elukerio\.org',
  381. r'(?:www\.)?yt\.lelux\.fi',
  382. r'(?:www\.)?invidious\.ggc-project\.de',
  383. r'(?:www\.)?yt\.maisputain\.ovh',
  384. r'(?:www\.)?ytprivate\.com',
  385. r'(?:www\.)?invidious\.13ad\.de',
  386. r'(?:www\.)?invidious\.toot\.koeln',
  387. r'(?:www\.)?invidious\.fdn\.fr',
  388. r'(?:www\.)?watch\.nettohikari\.com',
  389. r'(?:www\.)?invidious\.namazso\.eu',
  390. r'(?:www\.)?invidious\.silkky\.cloud',
  391. r'(?:www\.)?invidious\.exonip\.de',
  392. r'(?:www\.)?invidious\.riverside\.rocks',
  393. r'(?:www\.)?invidious\.blamefran\.net',
  394. r'(?:www\.)?invidious\.moomoo\.de',
  395. r'(?:www\.)?ytb\.trom\.tf',
  396. r'(?:www\.)?yt\.cyberhost\.uk',
  397. r'(?:www\.)?kgg2m7yk5aybusll\.onion',
  398. r'(?:www\.)?qklhadlycap4cnod\.onion',
  399. r'(?:www\.)?axqzx4s6s54s32yentfqojs3x5i7faxza6xo3ehd4bzzsg2ii4fv2iid\.onion',
  400. r'(?:www\.)?c7hqkpkpemu6e7emz5b4vyz7idjgdvgaaa3dyimmeojqbgpea3xqjoid\.onion',
  401. r'(?:www\.)?fz253lmuao3strwbfbmx46yu7acac2jz27iwtorgmbqlkurlclmancad\.onion',
  402. r'(?:www\.)?invidious\.l4qlywnpwqsluw65ts7md3khrivpirse744un3x7mlskqauz5pyuzgqd\.onion',
  403. r'(?:www\.)?owxfohz4kjyv25fvlqilyxast7inivgiktls3th44jhk3ej3i7ya\.b32\.i2p',
  404. r'(?:www\.)?4l2dgddgsrkf2ous66i6seeyi6etzfgrue332grh2n7madpwopotugyd\.onion',
  405. r'(?:www\.)?w6ijuptxiku4xpnnaetxvnkc5vqcdu7mgns2u77qefoixi63vbvnpnqd\.onion',
  406. r'(?:www\.)?kbjggqkzv65ivcqj6bumvp337z6264huv5kpkwuv6gu5yjiskvan7fad\.onion',
  407. r'(?:www\.)?grwp24hodrefzvjjuccrkw3mjq4tzhaaq32amf33dzpmuxe7ilepcmad\.onion',
  408. r'(?:www\.)?hpniueoejy4opn7bc4ftgazyqjoeqwlvh2uiku2xqku6zpoa4bf5ruid\.onion',
  409. )
  410. _VALID_URL = r"""(?x)^
  411. (
  412. (?:https?://|//) # http(s):// or protocol-independent URL
  413. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie|kids)?\.com|
  414. (?:www\.)?deturl\.com/www\.youtube\.com|
  415. (?:www\.)?pwnyoutube\.com|
  416. (?:www\.)?hooktube\.com|
  417. (?:www\.)?yourepeat\.com|
  418. tube\.majestyc\.net|
  419. %(invidious)s|
  420. youtube\.googleapis\.com)/ # the various hostnames, with wildcard subdomains
  421. (?:.*?\#/)? # handle anchor (#/) redirect urls
  422. (?: # the various things that can precede the ID:
  423. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  424. |shorts/
  425. |(?: # or the v= param in all its forms
  426. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  427. (?:\?|\#!?) # the params delimiter ? or # or #!
  428. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  429. v=
  430. )
  431. ))
  432. |(?:
  433. youtu\.be| # just youtu.be/xxxx
  434. vid\.plus| # or vid.plus/xxxx
  435. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  436. %(invidious)s
  437. )/
  438. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  439. )
  440. )? # all until now is optional -> you can pass the naked ID
  441. (?P<id>[0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  442. (?(1).+)? # if we found the ID, everything can follow
  443. $""" % {
  444. 'invidious': '|'.join(_INVIDIOUS_SITES),
  445. }
  446. _PLAYER_INFO_RE = (
  447. r'/s/player/(?P<id>[a-zA-Z0-9_-]{8,})/player',
  448. r'/(?P<id>[a-zA-Z0-9_-]{8,})/player(?:_ias\.vflset(?:/[a-zA-Z]{2,3}_[a-zA-Z]{2,3})?|-plasma-ias-(?:phone|tablet)-[a-z]{2}_[A-Z]{2}\.vflset)/base\.js$',
  449. r'\b(?P<id>vfl[a-zA-Z0-9_-]+)\b.*?\.js$',
  450. )
  451. _SUBTITLE_FORMATS = ('json3', 'srv1', 'srv2', 'srv3', 'ttml', 'vtt')
  452. _GEO_BYPASS = False
  453. IE_NAME = 'youtube'
  454. _TESTS = [
  455. {
  456. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  457. 'info_dict': {
  458. 'id': 'BaW_jenozKc',
  459. 'ext': 'mp4',
  460. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  461. 'uploader': 'Philipp Hagemeister',
  462. 'uploader_id': 'phihag',
  463. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  464. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  465. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  466. 'upload_date': '20121002',
  467. '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 .',
  468. 'categories': ['Science & Technology'],
  469. 'tags': ['youtube-dl'],
  470. 'duration': 10,
  471. 'view_count': int,
  472. 'like_count': int,
  473. 'dislike_count': int,
  474. 'start_time': 1,
  475. 'end_time': 9,
  476. }
  477. },
  478. {
  479. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  480. 'note': 'Embed-only video (#1746)',
  481. 'info_dict': {
  482. 'id': 'yZIXLfi8CZQ',
  483. 'ext': 'mp4',
  484. 'upload_date': '20120608',
  485. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  486. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  487. 'uploader': 'SET India',
  488. 'uploader_id': 'setindia',
  489. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
  490. 'age_limit': 18,
  491. },
  492. 'skip': 'Private video',
  493. },
  494. {
  495. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=yZIXLfi8CZQ',
  496. 'note': 'Use the first video ID in the URL',
  497. 'info_dict': {
  498. 'id': 'BaW_jenozKc',
  499. 'ext': 'mp4',
  500. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  501. 'uploader': 'Philipp Hagemeister',
  502. 'uploader_id': 'phihag',
  503. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  504. 'upload_date': '20121002',
  505. '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 .',
  506. 'categories': ['Science & Technology'],
  507. 'tags': ['youtube-dl'],
  508. 'duration': 10,
  509. 'view_count': int,
  510. 'like_count': int,
  511. 'dislike_count': int,
  512. },
  513. 'params': {
  514. 'skip_download': True,
  515. },
  516. },
  517. {
  518. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  519. 'note': '256k DASH audio (format 141) via DASH manifest',
  520. 'info_dict': {
  521. 'id': 'a9LDPn-MO4I',
  522. 'ext': 'm4a',
  523. 'upload_date': '20121002',
  524. 'uploader_id': '8KVIDEO',
  525. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  526. 'description': '',
  527. 'uploader': '8KVIDEO',
  528. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  529. },
  530. 'params': {
  531. 'youtube_include_dash_manifest': True,
  532. 'format': '141',
  533. },
  534. 'skip': 'format 141 not served anymore',
  535. },
  536. # DASH manifest with encrypted signature
  537. {
  538. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  539. 'info_dict': {
  540. 'id': 'IB3lcPjvWLA',
  541. 'ext': 'm4a',
  542. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  543. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  544. 'duration': 244,
  545. 'uploader': 'AfrojackVEVO',
  546. 'uploader_id': 'AfrojackVEVO',
  547. 'upload_date': '20131011',
  548. 'abr': 129.495,
  549. },
  550. 'params': {
  551. 'youtube_include_dash_manifest': True,
  552. 'format': '141/bestaudio[ext=m4a]',
  553. },
  554. },
  555. # Controversy video
  556. {
  557. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  558. 'info_dict': {
  559. 'id': 'T4XJQO3qol8',
  560. 'ext': 'mp4',
  561. 'duration': 219,
  562. 'upload_date': '20100909',
  563. 'uploader': 'Amazing Atheist',
  564. 'uploader_id': 'TheAmazingAtheist',
  565. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
  566. 'title': 'Burning Everyone\'s Koran',
  567. 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms \r\n\r\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',
  568. }
  569. },
  570. # Normal age-gate video (No vevo, embed allowed), available via embed page
  571. {
  572. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  573. 'info_dict': {
  574. 'id': 'HtVdAasjOgU',
  575. 'ext': 'mp4',
  576. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  577. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  578. 'duration': 142,
  579. 'uploader': 'The Witcher',
  580. 'uploader_id': 'WitcherGame',
  581. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
  582. 'upload_date': '20140605',
  583. 'age_limit': 18,
  584. },
  585. },
  586. {
  587. # Age-gated video only available with authentication (unavailable
  588. # via embed page workaround)
  589. 'url': 'XgnwCQzjau8',
  590. 'only_matching': True,
  591. },
  592. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  593. # YouTube Red ad is not captured for creator
  594. {
  595. 'url': '__2ABJjxzNo',
  596. 'info_dict': {
  597. 'id': '__2ABJjxzNo',
  598. 'ext': 'mp4',
  599. 'duration': 266,
  600. 'upload_date': '20100430',
  601. 'uploader_id': 'deadmau5',
  602. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
  603. 'creator': 'deadmau5',
  604. 'description': 'md5:6cbcd3a92ce1bc676fc4d6ab4ace2336',
  605. 'uploader': 'deadmau5',
  606. 'title': 'Deadmau5 - Some Chords (HD)',
  607. 'alt_title': 'Some Chords',
  608. },
  609. 'expected_warnings': [
  610. 'DASH manifest missing',
  611. ]
  612. },
  613. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  614. {
  615. 'url': 'lqQg6PlCWgI',
  616. 'info_dict': {
  617. 'id': 'lqQg6PlCWgI',
  618. 'ext': 'mp4',
  619. 'duration': 6085,
  620. 'upload_date': '20150827',
  621. 'uploader_id': 'olympic',
  622. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
  623. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  624. 'uploader': 'Olympic',
  625. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  626. },
  627. 'params': {
  628. 'skip_download': 'requires avconv',
  629. }
  630. },
  631. # Non-square pixels
  632. {
  633. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  634. 'info_dict': {
  635. 'id': '_b-2C3KPAM0',
  636. 'ext': 'mp4',
  637. 'stretched_ratio': 16 / 9.,
  638. 'duration': 85,
  639. 'upload_date': '20110310',
  640. 'uploader_id': 'AllenMeow',
  641. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
  642. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  643. 'uploader': '孫ᄋᄅ',
  644. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  645. },
  646. },
  647. # url_encoded_fmt_stream_map is empty string
  648. {
  649. 'url': 'qEJwOuvDf7I',
  650. 'info_dict': {
  651. 'id': 'qEJwOuvDf7I',
  652. 'ext': 'webm',
  653. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  654. 'description': '',
  655. 'upload_date': '20150404',
  656. 'uploader_id': 'spbelect',
  657. 'uploader': 'Наблюдатели Петербурга',
  658. },
  659. 'params': {
  660. 'skip_download': 'requires avconv',
  661. },
  662. 'skip': 'This live event has ended.',
  663. },
  664. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  665. {
  666. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  667. 'info_dict': {
  668. 'id': 'FIl7x6_3R5Y',
  669. 'ext': 'webm',
  670. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  671. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  672. 'duration': 220,
  673. 'upload_date': '20150625',
  674. 'uploader_id': 'dorappi2000',
  675. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  676. 'uploader': 'dorappi2000',
  677. 'formats': 'mincount:31',
  678. },
  679. 'skip': 'not actual anymore',
  680. },
  681. # DASH manifest with segment_list
  682. {
  683. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  684. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  685. 'info_dict': {
  686. 'id': 'CsmdDsKjzN8',
  687. 'ext': 'mp4',
  688. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  689. 'uploader': 'Airtek',
  690. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  691. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  692. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  693. },
  694. 'params': {
  695. 'youtube_include_dash_manifest': True,
  696. 'format': '135', # bestvideo
  697. },
  698. 'skip': 'This live event has ended.',
  699. },
  700. {
  701. # Multifeed videos (multiple cameras), URL is for Main Camera
  702. 'url': 'https://www.youtube.com/watch?v=jvGDaLqkpTg',
  703. 'info_dict': {
  704. 'id': 'jvGDaLqkpTg',
  705. 'title': 'Tom Clancy Free Weekend Rainbow Whatever',
  706. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  707. },
  708. 'playlist': [{
  709. 'info_dict': {
  710. 'id': 'jvGDaLqkpTg',
  711. 'ext': 'mp4',
  712. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Main Camera)',
  713. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  714. 'duration': 10643,
  715. 'upload_date': '20161111',
  716. 'uploader': 'Team PGP',
  717. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  718. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  719. },
  720. }, {
  721. 'info_dict': {
  722. 'id': '3AKt1R1aDnw',
  723. 'ext': 'mp4',
  724. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 2)',
  725. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  726. 'duration': 10991,
  727. 'upload_date': '20161111',
  728. 'uploader': 'Team PGP',
  729. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  730. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  731. },
  732. }, {
  733. 'info_dict': {
  734. 'id': 'RtAMM00gpVc',
  735. 'ext': 'mp4',
  736. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 3)',
  737. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  738. 'duration': 10995,
  739. 'upload_date': '20161111',
  740. 'uploader': 'Team PGP',
  741. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  742. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  743. },
  744. }, {
  745. 'info_dict': {
  746. 'id': '6N2fdlP3C5U',
  747. 'ext': 'mp4',
  748. 'title': 'Tom Clancy Free Weekend Rainbow Whatever (Camera 4)',
  749. 'description': 'md5:e03b909557865076822aa169218d6a5d',
  750. 'duration': 10990,
  751. 'upload_date': '20161111',
  752. 'uploader': 'Team PGP',
  753. 'uploader_id': 'UChORY56LMMETTuGjXaJXvLg',
  754. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UChORY56LMMETTuGjXaJXvLg',
  755. },
  756. }],
  757. 'params': {
  758. 'skip_download': True,
  759. },
  760. },
  761. {
  762. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  763. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  764. 'info_dict': {
  765. 'id': 'gVfLd0zydlo',
  766. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  767. },
  768. 'playlist_count': 2,
  769. 'skip': 'Not multifeed anymore',
  770. },
  771. {
  772. 'url': 'https://vid.plus/FlRa-iH7PGw',
  773. 'only_matching': True,
  774. },
  775. {
  776. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  777. 'only_matching': True,
  778. },
  779. {
  780. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  781. # Also tests cut-off URL expansion in video description (see
  782. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  783. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  784. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  785. 'info_dict': {
  786. 'id': 'lsguqyKfVQg',
  787. 'ext': 'mp4',
  788. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  789. 'alt_title': 'Dark Walk - Position Music',
  790. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  791. 'duration': 133,
  792. 'upload_date': '20151119',
  793. 'uploader_id': 'IronSoulElf',
  794. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
  795. 'uploader': 'IronSoulElf',
  796. 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  797. 'track': 'Dark Walk - Position Music',
  798. 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  799. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  800. },
  801. 'params': {
  802. 'skip_download': True,
  803. },
  804. },
  805. {
  806. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  807. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  808. 'only_matching': True,
  809. },
  810. {
  811. # Video with yt:stretch=17:0
  812. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  813. 'info_dict': {
  814. 'id': 'Q39EVAstoRM',
  815. 'ext': 'mp4',
  816. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  817. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  818. 'upload_date': '20151107',
  819. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  820. 'uploader': 'CH GAMER DROID',
  821. },
  822. 'params': {
  823. 'skip_download': True,
  824. },
  825. 'skip': 'This video does not exist.',
  826. },
  827. {
  828. # Video with incomplete 'yt:stretch=16:'
  829. 'url': 'https://www.youtube.com/watch?v=FRhJzUSJbGI',
  830. 'only_matching': True,
  831. },
  832. {
  833. # Video licensed under Creative Commons
  834. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  835. 'info_dict': {
  836. 'id': 'M4gD1WSo5mA',
  837. 'ext': 'mp4',
  838. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  839. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  840. 'duration': 721,
  841. 'upload_date': '20150127',
  842. 'uploader_id': 'BerkmanCenter',
  843. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
  844. 'uploader': 'The Berkman Klein Center for Internet & Society',
  845. 'license': 'Creative Commons Attribution license (reuse allowed)',
  846. },
  847. 'params': {
  848. 'skip_download': True,
  849. },
  850. },
  851. {
  852. # Channel-like uploader_url
  853. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  854. 'info_dict': {
  855. 'id': 'eQcmzGIKrzg',
  856. 'ext': 'mp4',
  857. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  858. 'description': 'md5:13a2503d7b5904ef4b223aa101628f39',
  859. 'duration': 4060,
  860. 'upload_date': '20151119',
  861. 'uploader': 'Bernie Sanders',
  862. 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
  863. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
  864. 'license': 'Creative Commons Attribution license (reuse allowed)',
  865. },
  866. 'params': {
  867. 'skip_download': True,
  868. },
  869. },
  870. {
  871. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  872. 'only_matching': True,
  873. },
  874. {
  875. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  876. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  877. 'only_matching': True,
  878. },
  879. {
  880. # Rental video preview
  881. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  882. 'info_dict': {
  883. 'id': 'uGpuVWrhIzE',
  884. 'ext': 'mp4',
  885. 'title': 'Piku - Trailer',
  886. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  887. 'upload_date': '20150811',
  888. 'uploader': 'FlixMatrix',
  889. 'uploader_id': 'FlixMatrixKaravan',
  890. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
  891. 'license': 'Standard YouTube License',
  892. },
  893. 'params': {
  894. 'skip_download': True,
  895. },
  896. 'skip': 'This video is not available.',
  897. },
  898. {
  899. # YouTube Red video with episode data
  900. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  901. 'info_dict': {
  902. 'id': 'iqKdEhx-dD4',
  903. 'ext': 'mp4',
  904. 'title': 'Isolation - Mind Field (Ep 1)',
  905. 'description': 'md5:f540112edec5d09fc8cc752d3d4ba3cd',
  906. 'duration': 2085,
  907. 'upload_date': '20170118',
  908. 'uploader': 'Vsauce',
  909. 'uploader_id': 'Vsauce',
  910. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
  911. 'series': 'Mind Field',
  912. 'season_number': 1,
  913. 'episode_number': 1,
  914. },
  915. 'params': {
  916. 'skip_download': True,
  917. },
  918. 'expected_warnings': [
  919. 'Skipping DASH manifest',
  920. ],
  921. },
  922. {
  923. # The following content has been identified by the YouTube community
  924. # as inappropriate or offensive to some audiences.
  925. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  926. 'info_dict': {
  927. 'id': '6SJNVb0GnPI',
  928. 'ext': 'mp4',
  929. 'title': 'Race Differences in Intelligence',
  930. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  931. 'duration': 965,
  932. 'upload_date': '20140124',
  933. 'uploader': 'New Century Foundation',
  934. 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
  935. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
  936. },
  937. 'params': {
  938. 'skip_download': True,
  939. },
  940. 'skip': 'This video has been removed for violating YouTube\'s policy on hate speech.',
  941. },
  942. {
  943. # itag 212
  944. 'url': '1t24XAntNCY',
  945. 'only_matching': True,
  946. },
  947. {
  948. # geo restricted to JP
  949. 'url': 'sJL6WA-aGkQ',
  950. 'only_matching': True,
  951. },
  952. {
  953. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  954. 'only_matching': True,
  955. },
  956. {
  957. 'url': 'https://redirect.invidious.io/watch?v=BaW_jenozKc',
  958. 'only_matching': True,
  959. },
  960. {
  961. # from https://nitter.pussthecat.org/YouTube/status/1360363141947944964#m
  962. 'url': 'https://redirect.invidious.io/Yh0AhrY9GjA',
  963. 'only_matching': True,
  964. },
  965. {
  966. # DRM protected
  967. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  968. 'only_matching': True,
  969. },
  970. {
  971. # Video with unsupported adaptive stream type formats
  972. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  973. 'info_dict': {
  974. 'id': 'Z4Vy8R84T1U',
  975. 'ext': 'mp4',
  976. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  977. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  978. 'duration': 433,
  979. 'upload_date': '20130923',
  980. 'uploader': 'Amelia Putri Harwita',
  981. 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
  982. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
  983. 'formats': 'maxcount:10',
  984. },
  985. 'params': {
  986. 'skip_download': True,
  987. 'youtube_include_dash_manifest': False,
  988. },
  989. 'skip': 'not actual anymore',
  990. },
  991. {
  992. # Youtube Music Auto-generated description
  993. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  994. 'info_dict': {
  995. 'id': 'MgNrAu2pzNs',
  996. 'ext': 'mp4',
  997. 'title': 'Voyeur Girl',
  998. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  999. 'upload_date': '20190312',
  1000. 'uploader': 'Stephen - Topic',
  1001. 'uploader_id': 'UC-pWHpBjdGG69N9mM2auIAA',
  1002. 'artist': 'Stephen',
  1003. 'track': 'Voyeur Girl',
  1004. 'album': 'it\'s too much love to know my dear',
  1005. 'release_date': '20190313',
  1006. 'release_year': 2019,
  1007. },
  1008. 'params': {
  1009. 'skip_download': True,
  1010. },
  1011. },
  1012. {
  1013. 'url': 'https://www.youtubekids.com/watch?v=3b8nCWDgZ6Q',
  1014. 'only_matching': True,
  1015. },
  1016. {
  1017. # invalid -> valid video id redirection
  1018. 'url': 'DJztXj2GPfl',
  1019. 'info_dict': {
  1020. 'id': 'DJztXj2GPfk',
  1021. 'ext': 'mp4',
  1022. 'title': 'Panjabi MC - Mundian To Bach Ke (The Dictator Soundtrack)',
  1023. 'description': 'md5:bf577a41da97918e94fa9798d9228825',
  1024. 'upload_date': '20090125',
  1025. 'uploader': 'Prochorowka',
  1026. 'uploader_id': 'Prochorowka',
  1027. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Prochorowka',
  1028. 'artist': 'Panjabi MC',
  1029. 'track': 'Beware of the Boys (Mundian to Bach Ke) - Motivo Hi-Lectro Remix',
  1030. 'album': 'Beware of the Boys (Mundian To Bach Ke)',
  1031. },
  1032. 'params': {
  1033. 'skip_download': True,
  1034. },
  1035. 'skip': 'Video unavailable',
  1036. },
  1037. {
  1038. # empty description results in an empty string
  1039. 'url': 'https://www.youtube.com/watch?v=x41yOUIvK2k',
  1040. 'info_dict': {
  1041. 'id': 'x41yOUIvK2k',
  1042. 'ext': 'mp4',
  1043. 'title': 'IMG 3456',
  1044. 'description': '',
  1045. 'upload_date': '20170613',
  1046. 'uploader_id': 'ElevageOrVert',
  1047. 'uploader': 'ElevageOrVert',
  1048. },
  1049. 'params': {
  1050. 'skip_download': True,
  1051. },
  1052. },
  1053. {
  1054. # with '};' inside yt initial data (see [1])
  1055. # see [2] for an example with '};' inside ytInitialPlayerResponse
  1056. # 1. https://github.com/ytdl-org/youtube-dl/issues/27093
  1057. # 2. https://github.com/ytdl-org/youtube-dl/issues/27216
  1058. 'url': 'https://www.youtube.com/watch?v=CHqg6qOn4no',
  1059. 'info_dict': {
  1060. 'id': 'CHqg6qOn4no',
  1061. 'ext': 'mp4',
  1062. 'title': 'Part 77 Sort a list of simple types in c#',
  1063. 'description': 'md5:b8746fa52e10cdbf47997903f13b20dc',
  1064. 'upload_date': '20130831',
  1065. 'uploader_id': 'kudvenkat',
  1066. 'uploader': 'kudvenkat',
  1067. },
  1068. 'params': {
  1069. 'skip_download': True,
  1070. },
  1071. },
  1072. {
  1073. # another example of '};' in ytInitialData
  1074. 'url': 'https://www.youtube.com/watch?v=gVfgbahppCY',
  1075. 'only_matching': True,
  1076. },
  1077. {
  1078. 'url': 'https://www.youtube.com/watch_popup?v=63RmMXCd_bQ',
  1079. 'only_matching': True,
  1080. },
  1081. {
  1082. # https://github.com/ytdl-org/youtube-dl/pull/28094
  1083. 'url': 'OtqTfy26tG0',
  1084. 'info_dict': {
  1085. 'id': 'OtqTfy26tG0',
  1086. 'ext': 'mp4',
  1087. 'title': 'Burn Out',
  1088. 'description': 'md5:8d07b84dcbcbfb34bc12a56d968b6131',
  1089. 'upload_date': '20141120',
  1090. 'uploader': 'The Cinematic Orchestra - Topic',
  1091. 'uploader_id': 'UCIzsJBIyo8hhpFm1NK0uLgw',
  1092. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCIzsJBIyo8hhpFm1NK0uLgw',
  1093. 'artist': 'The Cinematic Orchestra',
  1094. 'track': 'Burn Out',
  1095. 'album': 'Every Day',
  1096. 'release_data': None,
  1097. 'release_year': None,
  1098. },
  1099. 'params': {
  1100. 'skip_download': True,
  1101. },
  1102. },
  1103. {
  1104. # controversial video, only works with bpctr when authenticated with cookies
  1105. 'url': 'https://www.youtube.com/watch?v=nGC3D_FkCmg',
  1106. 'only_matching': True,
  1107. },
  1108. {
  1109. # restricted location, https://github.com/ytdl-org/youtube-dl/issues/28685
  1110. 'url': 'cBvYw8_A0vQ',
  1111. 'info_dict': {
  1112. 'id': 'cBvYw8_A0vQ',
  1113. 'ext': 'mp4',
  1114. 'title': '4K Ueno Okachimachi Street Scenes 上野御徒町歩き',
  1115. 'description': 'md5:ea770e474b7cd6722b4c95b833c03630',
  1116. 'upload_date': '20201120',
  1117. 'uploader': 'Walk around Japan',
  1118. 'uploader_id': 'UC3o_t8PzBmXf5S9b7GLx1Mw',
  1119. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UC3o_t8PzBmXf5S9b7GLx1Mw',
  1120. },
  1121. 'params': {
  1122. 'skip_download': True,
  1123. },
  1124. },
  1125. {
  1126. # YT 'Shorts'
  1127. 'url': 'https://youtube.com/shorts/4L2J27mJ3Dc',
  1128. 'info_dict': {
  1129. 'id': '4L2J27mJ3Dc',
  1130. 'ext': 'mp4',
  1131. 'upload_date': '20211025',
  1132. 'uploader': 'Charlie Berens',
  1133. 'description': 'md5:976512b8a29269b93bbd8a61edc45a6d',
  1134. 'uploader_id': 'fivedlrmilkshake',
  1135. 'title': 'Midwest Squid Game #Shorts',
  1136. },
  1137. 'params': {
  1138. 'skip_download': True,
  1139. },
  1140. },
  1141. ]
  1142. _formats = {
  1143. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1144. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  1145. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  1146. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  1147. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  1148. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1149. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1150. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1151. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  1152. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  1153. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1154. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  1155. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1156. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  1157. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1158. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  1159. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1160. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  1161. # 3D videos
  1162. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1163. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  1164. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1165. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  1166. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  1167. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1168. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  1169. # Apple HTTP Live Streaming
  1170. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1171. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1172. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1173. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  1174. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1175. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  1176. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  1177. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  1178. # DASH mp4 video
  1179. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1180. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1181. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1182. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1183. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1184. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  1185. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1186. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1187. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1188. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1189. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  1190. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  1191. # Dash mp4 audio
  1192. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  1193. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  1194. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  1195. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1196. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  1197. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  1198. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  1199. # Dash webm
  1200. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1201. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1202. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1203. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1204. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1205. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  1206. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  1207. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1208. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1209. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1210. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1211. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1212. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1213. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1214. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1215. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  1216. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1217. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1218. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1219. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1220. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  1221. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  1222. # Dash webm audio
  1223. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  1224. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  1225. # Dash webm audio with opus inside
  1226. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  1227. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  1228. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  1229. # RTMP (unnamed)
  1230. '_rtmp': {'protocol': 'rtmp'},
  1231. # av01 video only formats sometimes served with "unknown" codecs
  1232. '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1233. '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1234. '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1235. '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  1236. }
  1237. @classmethod
  1238. def suitable(cls, url):
  1239. # Hack for lazy extractors until more generic solution is implemented
  1240. # (see #28780)
  1241. from .youtube import parse_qs
  1242. qs = parse_qs(url)
  1243. if qs.get('list', [None])[0]:
  1244. return False
  1245. return super(YoutubeIE, cls).suitable(url)
  1246. def __init__(self, *args, **kwargs):
  1247. super(YoutubeIE, self).__init__(*args, **kwargs)
  1248. self._code_cache = {}
  1249. self._player_cache = {}
  1250. def _signature_cache_id(self, example_sig):
  1251. """ Return a string representation of a signature """
  1252. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  1253. @classmethod
  1254. def _extract_player_info(cls, player_url):
  1255. for player_re in cls._PLAYER_INFO_RE:
  1256. id_m = re.search(player_re, player_url)
  1257. if id_m:
  1258. break
  1259. else:
  1260. raise ExtractorError('Cannot identify player %r' % player_url)
  1261. return id_m.group('id')
  1262. def _get_player_code(self, video_id, player_url, player_id=None):
  1263. if not player_id:
  1264. player_id = self._extract_player_info(player_url)
  1265. if player_id not in self._code_cache:
  1266. self._code_cache[player_id] = self._download_webpage(
  1267. player_url, video_id,
  1268. note='Downloading player ' + player_id,
  1269. errnote='Download of %s failed' % player_url)
  1270. return self._code_cache[player_id]
  1271. def _extract_signature_function(self, video_id, player_url, example_sig):
  1272. player_id = self._extract_player_info(player_url)
  1273. # Read from filesystem cache
  1274. func_id = 'js_%s_%s' % (
  1275. player_id, self._signature_cache_id(example_sig))
  1276. assert os.path.basename(func_id) == func_id
  1277. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  1278. if cache_spec is not None:
  1279. return lambda s: ''.join(s[i] for i in cache_spec)
  1280. code = self._get_player_code(video_id, player_url, player_id)
  1281. res = self._parse_sig_js(code)
  1282. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1283. cache_res = res(test_string)
  1284. cache_spec = [ord(c) for c in cache_res]
  1285. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  1286. return res
  1287. def _print_sig_code(self, func, example_sig):
  1288. def gen_sig_code(idxs):
  1289. def _genslice(start, end, step):
  1290. starts = '' if start == 0 else str(start)
  1291. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  1292. steps = '' if step == 1 else (':%d' % step)
  1293. return 's[%s%s%s]' % (starts, ends, steps)
  1294. step = None
  1295. # Quelch pyflakes warnings - start will be set when step is set
  1296. start = '(Never used)'
  1297. for i, prev in zip(idxs[1:], idxs[:-1]):
  1298. if step is not None:
  1299. if i - prev == step:
  1300. continue
  1301. yield _genslice(start, prev, step)
  1302. step = None
  1303. continue
  1304. if i - prev in [-1, 1]:
  1305. step = i - prev
  1306. start = prev
  1307. continue
  1308. else:
  1309. yield 's[%d]' % prev
  1310. if step is None:
  1311. yield 's[%d]' % i
  1312. else:
  1313. yield _genslice(start, i, step)
  1314. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1315. cache_res = func(test_string)
  1316. cache_spec = [ord(c) for c in cache_res]
  1317. expr_code = ' + '.join(gen_sig_code(cache_spec))
  1318. signature_id_tuple = '(%s)' % (
  1319. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  1320. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  1321. ' return %s\n') % (signature_id_tuple, expr_code)
  1322. self.to_screen('Extracted signature function:\n' + code)
  1323. def _parse_sig_js(self, jscode):
  1324. funcname = self._search_regex(
  1325. (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1326. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1327. r'\bm=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(h\.s\)\)',
  1328. r'\bc&&\(c=(?P<sig>[a-zA-Z0-9$]{2,})\(decodeURIComponent\(c\)\)',
  1329. r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\);[a-zA-Z0-9$]{2}\.[a-zA-Z0-9$]{2}\(a,\d+\)',
  1330. r'(?:\b|[^a-zA-Z0-9$])(?P<sig>[a-zA-Z0-9$]{2,})\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1331. r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1332. # Obsolete patterns
  1333. r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1334. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1335. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1336. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1337. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1338. r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1339. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1340. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
  1341. jscode, 'Initial JS player signature function name', group='sig')
  1342. jsi = JSInterpreter(jscode)
  1343. initial_function = jsi.extract_function(funcname)
  1344. return lambda s: initial_function([s])
  1345. def _decrypt_signature(self, s, video_id, player_url):
  1346. """Turn the encrypted s field into a working signature"""
  1347. if player_url is None:
  1348. raise ExtractorError('Cannot decrypt signature without player_url')
  1349. try:
  1350. player_id = (player_url, self._signature_cache_id(s))
  1351. if player_id not in self._player_cache:
  1352. func = self._extract_signature_function(
  1353. video_id, player_url, s
  1354. )
  1355. self._player_cache[player_id] = func
  1356. func = self._player_cache[player_id]
  1357. if self._downloader.params.get('youtube_print_sig_code'):
  1358. self._print_sig_code(func, s)
  1359. return func(s)
  1360. except Exception as e:
  1361. tb = traceback.format_exc()
  1362. raise ExtractorError(
  1363. 'Signature extraction failed: ' + tb, cause=e)
  1364. def _extract_player_url(self, webpage):
  1365. player_url = self._search_regex(
  1366. r'"(?:PLAYER_JS_URL|jsUrl)"\s*:\s*"([^"]+)"',
  1367. webpage or '', 'player URL', fatal=False)
  1368. if not player_url:
  1369. return
  1370. if player_url.startswith('//'):
  1371. player_url = 'https:' + player_url
  1372. elif not re.match(r'https?://', player_url):
  1373. player_url = compat_urlparse.urljoin(
  1374. 'https://www.youtube.com', player_url)
  1375. return player_url
  1376. # from yt-dlp
  1377. # See also:
  1378. # 1. https://github.com/ytdl-org/youtube-dl/issues/29326#issuecomment-894619419
  1379. # 2. https://code.videolan.org/videolan/vlc/-/blob/4fb284e5af69aa9ac2100ccbdd3b88debec9987f/share/lua/playlist/youtube.lua#L116
  1380. # 3. https://github.com/ytdl-org/youtube-dl/issues/30097#issuecomment-950157377
  1381. def _extract_n_function_name(self, jscode):
  1382. target = r'(?P<nfunc>[a-zA-Z_$][\w$]*)(?:\[(?P<idx>\d+)\])?'
  1383. nfunc_and_idx = self._search_regex(
  1384. r'\.get\("n"\)\)&&\(b=(%s)\([\w$]+\)' % (target, ),
  1385. jscode, 'Initial JS player n function name')
  1386. nfunc, idx = re.match(target, nfunc_and_idx).group('nfunc', 'idx')
  1387. if not idx:
  1388. return nfunc
  1389. if int_or_none(idx) == 0:
  1390. real_nfunc = self._search_regex(
  1391. r'var %s\s*=\s*\[([a-zA-Z_$][\w$]*)\];' % (re.escape(nfunc), ), jscode,
  1392. 'Initial JS player n function alias ({nfunc}[{idx}])'.format(**locals()))
  1393. if real_nfunc:
  1394. return real_nfunc
  1395. return self._parse_json(self._search_regex(
  1396. r'var %s\s*=\s*(\[.+?\]);' % (re.escape(nfunc), ), jscode,
  1397. 'Initial JS player n function name ({nfunc}[{idx}])'.format(**locals())), nfunc, transform_source=js_to_json)[int(idx)]
  1398. def _extract_n_function(self, video_id, player_url):
  1399. player_id = self._extract_player_info(player_url)
  1400. func_code = self._downloader.cache.load('youtube-nsig', player_id)
  1401. if func_code:
  1402. jsi = JSInterpreter(func_code)
  1403. else:
  1404. jscode = self._get_player_code(video_id, player_url, player_id)
  1405. funcname = self._extract_n_function_name(jscode)
  1406. jsi = JSInterpreter(jscode)
  1407. func_code = jsi.extract_function_code(funcname)
  1408. self._downloader.cache.store('youtube-nsig', player_id, func_code)
  1409. if self._downloader.params.get('youtube_print_sig_code'):
  1410. self.to_screen('Extracted nsig function from {0}:\n{1}\n'.format(player_id, func_code[1]))
  1411. return lambda s: jsi.extract_function_from_code(*func_code)([s])
  1412. def _n_descramble(self, n_param, player_url, video_id):
  1413. """Compute the response to YT's "n" parameter challenge,
  1414. or None
  1415. Args:
  1416. n_param -- challenge string that is the value of the
  1417. URL's "n" query parameter
  1418. player_url -- URL of YT player JS
  1419. video_id
  1420. """
  1421. sig_id = ('nsig_value', n_param)
  1422. if sig_id in self._player_cache:
  1423. return self._player_cache[sig_id]
  1424. try:
  1425. player_id = ('nsig', player_url)
  1426. if player_id not in self._player_cache:
  1427. self._player_cache[player_id] = self._extract_n_function(video_id, player_url)
  1428. func = self._player_cache[player_id]
  1429. ret = func(n_param)
  1430. if ret.startswith('enhanced_except_'):
  1431. raise ExtractorError('Unhandled exception in decode')
  1432. self._player_cache[sig_id] = ret
  1433. if self._downloader.params.get('verbose', False):
  1434. self._downloader.to_screen('[debug] [%s] %s' % (self.IE_NAME, 'Decrypted nsig {0} => {1}'.format(n_param, self._player_cache[sig_id])))
  1435. return self._player_cache[sig_id]
  1436. except Exception as e:
  1437. self._downloader.report_warning(
  1438. '[%s] %s (%s %s)' % (
  1439. self.IE_NAME,
  1440. 'Unable to decode n-parameter: download likely to be throttled',
  1441. error_to_compat_str(e),
  1442. traceback.format_exc()))
  1443. def _unthrottle_format_urls(self, video_id, player_url, formats):
  1444. for fmt in formats:
  1445. parsed_fmt_url = compat_urlparse.urlparse(fmt['url'])
  1446. qs = compat_urlparse.parse_qs(parsed_fmt_url.query)
  1447. n_param = qs.get('n')
  1448. if not n_param:
  1449. continue
  1450. n_param = n_param[-1]
  1451. n_response = self._n_descramble(n_param, player_url, video_id)
  1452. if n_response is None:
  1453. # give up if descrambling failed
  1454. break
  1455. qs['n'] = [n_response]
  1456. fmt['url'] = compat_urlparse.urlunparse(
  1457. parsed_fmt_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1458. def _mark_watched(self, video_id, player_response):
  1459. playback_url = url_or_none(try_get(
  1460. player_response,
  1461. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']))
  1462. if not playback_url:
  1463. return
  1464. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1465. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1466. # cpn generation algorithm is reverse engineered from base.js.
  1467. # In fact it works even with dummy cpn.
  1468. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1469. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1470. qs.update({
  1471. 'ver': ['2'],
  1472. 'cpn': [cpn],
  1473. })
  1474. playback_url = compat_urlparse.urlunparse(
  1475. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1476. self._download_webpage(
  1477. playback_url, video_id, 'Marking watched',
  1478. 'Unable to mark watched', fatal=False)
  1479. @staticmethod
  1480. def _extract_urls(webpage):
  1481. # Embedded YouTube player
  1482. entries = [
  1483. unescapeHTML(mobj.group('url'))
  1484. for mobj in re.finditer(r'''(?x)
  1485. (?:
  1486. <iframe[^>]+?src=|
  1487. data-video-url=|
  1488. <embed[^>]+?src=|
  1489. embedSWF\(?:\s*|
  1490. <object[^>]+data=|
  1491. new\s+SWFObject\(
  1492. )
  1493. (["\'])
  1494. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1495. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1496. \1''', webpage)]
  1497. # lazyYT YouTube embed
  1498. entries.extend(list(map(
  1499. unescapeHTML,
  1500. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  1501. # Wordpress "YouTube Video Importer" plugin
  1502. matches = re.findall(r'''(?x)<div[^>]+
  1503. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  1504. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  1505. entries.extend(m[-1] for m in matches)
  1506. return entries
  1507. @staticmethod
  1508. def _extract_url(webpage):
  1509. urls = YoutubeIE._extract_urls(webpage)
  1510. return urls[0] if urls else None
  1511. @classmethod
  1512. def extract_id(cls, url):
  1513. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1514. if mobj is None:
  1515. raise ExtractorError('Invalid URL: %s' % url)
  1516. video_id = mobj.group(2)
  1517. return video_id
  1518. def _extract_chapters_from_json(self, data, video_id, duration):
  1519. chapters_list = try_get(
  1520. data,
  1521. lambda x: x['playerOverlays']
  1522. ['playerOverlayRenderer']
  1523. ['decoratedPlayerBarRenderer']
  1524. ['decoratedPlayerBarRenderer']
  1525. ['playerBar']
  1526. ['chapteredPlayerBarRenderer']
  1527. ['chapters'],
  1528. list)
  1529. if not chapters_list:
  1530. return
  1531. def chapter_time(chapter):
  1532. return float_or_none(
  1533. try_get(
  1534. chapter,
  1535. lambda x: x['chapterRenderer']['timeRangeStartMillis'],
  1536. int),
  1537. scale=1000)
  1538. chapters = []
  1539. for next_num, chapter in enumerate(chapters_list, start=1):
  1540. start_time = chapter_time(chapter)
  1541. if start_time is None:
  1542. continue
  1543. end_time = (chapter_time(chapters_list[next_num])
  1544. if next_num < len(chapters_list) else duration)
  1545. if end_time is None:
  1546. continue
  1547. title = try_get(
  1548. chapter, lambda x: x['chapterRenderer']['title']['simpleText'],
  1549. compat_str)
  1550. chapters.append({
  1551. 'start_time': start_time,
  1552. 'end_time': end_time,
  1553. 'title': title,
  1554. })
  1555. return chapters
  1556. def _extract_yt_initial_variable(self, webpage, regex, video_id, name):
  1557. return self._parse_json(self._search_regex(
  1558. (r'%s\s*%s' % (regex, self._YT_INITIAL_BOUNDARY_RE),
  1559. regex), webpage, name, default='{}'), video_id, fatal=False)
  1560. def _real_extract(self, url):
  1561. url, smuggled_data = unsmuggle_url(url, {})
  1562. video_id = self._match_id(url)
  1563. base_url = self.http_scheme() + '//www.youtube.com/'
  1564. webpage_url = base_url + 'watch?v=' + video_id
  1565. webpage = self._download_webpage(
  1566. webpage_url + '&bpctr=9999999999&has_verified=1', video_id, fatal=False)
  1567. player_response = None
  1568. if webpage:
  1569. player_response = self._extract_yt_initial_variable(
  1570. webpage, self._YT_INITIAL_PLAYER_RESPONSE_RE,
  1571. video_id, 'initial player response')
  1572. if not player_response:
  1573. player_response = self._call_api(
  1574. 'player', {'videoId': video_id}, video_id)
  1575. playability_status = player_response.get('playabilityStatus') or {}
  1576. if playability_status.get('reason') == 'Sign in to confirm your age':
  1577. video_info = self._download_webpage(
  1578. base_url + 'get_video_info', video_id,
  1579. 'Refetching age-gated info webpage',
  1580. 'unable to download video info webpage', query={
  1581. 'video_id': video_id,
  1582. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1583. 'html5': 1,
  1584. # See https://github.com/ytdl-org/youtube-dl/issues/29333#issuecomment-864049544
  1585. 'c': 'TVHTML5',
  1586. 'cver': '6.20180913',
  1587. }, fatal=False)
  1588. if video_info:
  1589. pr = self._parse_json(
  1590. try_get(
  1591. compat_parse_qs(video_info),
  1592. lambda x: x['player_response'][0], compat_str) or '{}',
  1593. video_id, fatal=False)
  1594. if pr and isinstance(pr, dict):
  1595. player_response = pr
  1596. trailer_video_id = try_get(
  1597. playability_status,
  1598. lambda x: x['errorScreen']['playerLegacyDesktopYpcTrailerRenderer']['trailerVideoId'],
  1599. compat_str)
  1600. if trailer_video_id:
  1601. return self.url_result(
  1602. trailer_video_id, self.ie_key(), trailer_video_id)
  1603. def get_text(x):
  1604. if not x:
  1605. return
  1606. text = x.get('simpleText')
  1607. if text and isinstance(text, compat_str):
  1608. return text
  1609. runs = x.get('runs')
  1610. if not isinstance(runs, list):
  1611. return
  1612. return ''.join([r['text'] for r in runs if isinstance(r.get('text'), compat_str)])
  1613. search_meta = (
  1614. lambda x: self._html_search_meta(x, webpage, default=None)) \
  1615. if webpage else lambda x: None
  1616. video_details = player_response.get('videoDetails') or {}
  1617. microformat = try_get(
  1618. player_response,
  1619. lambda x: x['microformat']['playerMicroformatRenderer'],
  1620. dict) or {}
  1621. video_title = video_details.get('title') \
  1622. or get_text(microformat.get('title')) \
  1623. or search_meta(['og:title', 'twitter:title', 'title'])
  1624. video_description = video_details.get('shortDescription')
  1625. if not smuggled_data.get('force_singlefeed', False):
  1626. if not self._downloader.params.get('noplaylist'):
  1627. multifeed_metadata_list = try_get(
  1628. player_response,
  1629. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1630. compat_str)
  1631. if multifeed_metadata_list:
  1632. entries = []
  1633. feed_ids = []
  1634. for feed in multifeed_metadata_list.split(','):
  1635. # Unquote should take place before split on comma (,) since textual
  1636. # fields may contain comma as well (see
  1637. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1638. feed_data = compat_parse_qs(
  1639. compat_urllib_parse_unquote_plus(feed))
  1640. def feed_entry(name):
  1641. return try_get(
  1642. feed_data, lambda x: x[name][0], compat_str)
  1643. feed_id = feed_entry('id')
  1644. if not feed_id:
  1645. continue
  1646. feed_title = feed_entry('title')
  1647. title = video_title
  1648. if feed_title:
  1649. title += ' (%s)' % feed_title
  1650. entries.append({
  1651. '_type': 'url_transparent',
  1652. 'ie_key': 'Youtube',
  1653. 'url': smuggle_url(
  1654. base_url + 'watch?v=' + feed_data['id'][0],
  1655. {'force_singlefeed': True}),
  1656. 'title': title,
  1657. })
  1658. feed_ids.append(feed_id)
  1659. self.to_screen(
  1660. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1661. % (', '.join(feed_ids), video_id))
  1662. return self.playlist_result(
  1663. entries, video_id, video_title, video_description)
  1664. else:
  1665. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1666. formats = []
  1667. itags = []
  1668. itag_qualities = {}
  1669. player_url = None
  1670. q = qualities(['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'])
  1671. streaming_data = player_response.get('streamingData') or {}
  1672. streaming_formats = streaming_data.get('formats') or []
  1673. streaming_formats.extend(streaming_data.get('adaptiveFormats') or [])
  1674. for fmt in streaming_formats:
  1675. if fmt.get('targetDurationSec') or fmt.get('drmFamilies'):
  1676. continue
  1677. itag = str_or_none(fmt.get('itag'))
  1678. quality = fmt.get('quality')
  1679. if itag and quality:
  1680. itag_qualities[itag] = quality
  1681. # FORMAT_STREAM_TYPE_OTF(otf=1) requires downloading the init fragment
  1682. # (adding `&sq=0` to the URL) and parsing emsg box to determine the
  1683. # number of fragment that would subsequently requested with (`&sq=N`)
  1684. if fmt.get('type') == 'FORMAT_STREAM_TYPE_OTF':
  1685. continue
  1686. fmt_url = fmt.get('url')
  1687. if not fmt_url:
  1688. sc = compat_parse_qs(fmt.get('signatureCipher'))
  1689. fmt_url = url_or_none(try_get(sc, lambda x: x['url'][0]))
  1690. encrypted_sig = try_get(sc, lambda x: x['s'][0])
  1691. if not (sc and fmt_url and encrypted_sig):
  1692. continue
  1693. if not player_url:
  1694. player_url = self._extract_player_url(webpage)
  1695. if not player_url:
  1696. continue
  1697. signature = self._decrypt_signature(sc['s'][0], video_id, player_url)
  1698. sp = try_get(sc, lambda x: x['sp'][0]) or 'signature'
  1699. fmt_url += '&' + sp + '=' + signature
  1700. if itag:
  1701. itags.append(itag)
  1702. tbr = float_or_none(
  1703. fmt.get('averageBitrate') or fmt.get('bitrate'), 1000)
  1704. dct = {
  1705. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1706. 'filesize': int_or_none(fmt.get('contentLength')),
  1707. 'format_id': itag,
  1708. 'format_note': fmt.get('qualityLabel') or quality,
  1709. 'fps': int_or_none(fmt.get('fps')),
  1710. 'height': int_or_none(fmt.get('height')),
  1711. 'quality': q(quality),
  1712. 'tbr': tbr,
  1713. 'url': fmt_url,
  1714. 'width': fmt.get('width'),
  1715. }
  1716. mimetype = fmt.get('mimeType')
  1717. if mimetype:
  1718. mobj = re.match(
  1719. r'((?:[^/]+)/(?:[^;]+))(?:;\s*codecs="([^"]+)")?', mimetype)
  1720. if mobj:
  1721. dct['ext'] = mimetype2ext(mobj.group(1))
  1722. dct.update(parse_codecs(mobj.group(2)))
  1723. no_audio = dct.get('acodec') == 'none'
  1724. no_video = dct.get('vcodec') == 'none'
  1725. if no_audio:
  1726. dct['vbr'] = tbr
  1727. if no_video:
  1728. dct['abr'] = tbr
  1729. if no_audio or no_video:
  1730. dct['downloader_options'] = {
  1731. # Youtube throttles chunks >~10M
  1732. 'http_chunk_size': 10485760,
  1733. }
  1734. if dct.get('ext'):
  1735. dct['container'] = dct['ext'] + '_dash'
  1736. formats.append(dct)
  1737. hls_manifest_url = streaming_data.get('hlsManifestUrl')
  1738. if hls_manifest_url:
  1739. for f in self._extract_m3u8_formats(
  1740. hls_manifest_url, video_id, 'mp4', fatal=False):
  1741. itag = self._search_regex(
  1742. r'/itag/(\d+)', f['url'], 'itag', default=None)
  1743. if itag:
  1744. f['format_id'] = itag
  1745. formats.append(f)
  1746. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1747. dash_manifest_url = streaming_data.get('dashManifestUrl')
  1748. if dash_manifest_url:
  1749. for f in self._extract_mpd_formats(
  1750. dash_manifest_url, video_id, fatal=False):
  1751. itag = f['format_id']
  1752. if itag in itags:
  1753. continue
  1754. if itag in itag_qualities:
  1755. f['quality'] = q(itag_qualities[itag])
  1756. filesize = int_or_none(self._search_regex(
  1757. r'/clen/(\d+)', f.get('fragment_base_url')
  1758. or f['url'], 'file size', default=None))
  1759. if filesize:
  1760. f['filesize'] = filesize
  1761. formats.append(f)
  1762. if not formats:
  1763. if streaming_data.get('licenseInfos'):
  1764. raise ExtractorError(
  1765. 'This video is DRM protected.', expected=True)
  1766. pemr = try_get(
  1767. playability_status,
  1768. lambda x: x['errorScreen']['playerErrorMessageRenderer'],
  1769. dict) or {}
  1770. reason = get_text(pemr.get('reason')) or playability_status.get('reason')
  1771. subreason = pemr.get('subreason')
  1772. if subreason:
  1773. subreason = clean_html(get_text(subreason))
  1774. if subreason == 'The uploader has not made this video available in your country.':
  1775. countries = microformat.get('availableCountries')
  1776. if not countries:
  1777. regions_allowed = search_meta('regionsAllowed')
  1778. countries = regions_allowed.split(',') if regions_allowed else None
  1779. self.raise_geo_restricted(
  1780. subreason, countries)
  1781. reason += '\n' + subreason
  1782. if reason:
  1783. raise ExtractorError(reason, expected=True)
  1784. self._sort_formats(formats)
  1785. keywords = video_details.get('keywords') or []
  1786. if not keywords and webpage:
  1787. keywords = [
  1788. unescapeHTML(m.group('content'))
  1789. for m in re.finditer(self._meta_regex('og:video:tag'), webpage)]
  1790. for keyword in keywords:
  1791. if keyword.startswith('yt:stretch='):
  1792. mobj = re.search(r'(\d+)\s*:\s*(\d+)', keyword)
  1793. if mobj:
  1794. # NB: float is intentional for forcing float division
  1795. w, h = (float(v) for v in mobj.groups())
  1796. if w > 0 and h > 0:
  1797. ratio = w / h
  1798. for f in formats:
  1799. if f.get('vcodec') != 'none':
  1800. f['stretched_ratio'] = ratio
  1801. break
  1802. thumbnails = []
  1803. for container in (video_details, microformat):
  1804. for thumbnail in (try_get(
  1805. container,
  1806. lambda x: x['thumbnail']['thumbnails'], list) or []):
  1807. thumbnail_url = thumbnail.get('url')
  1808. if not thumbnail_url:
  1809. continue
  1810. thumbnails.append({
  1811. 'height': int_or_none(thumbnail.get('height')),
  1812. 'url': thumbnail_url,
  1813. 'width': int_or_none(thumbnail.get('width')),
  1814. })
  1815. if thumbnails:
  1816. break
  1817. else:
  1818. thumbnail = search_meta(['og:image', 'twitter:image'])
  1819. if thumbnail:
  1820. thumbnails = [{'url': thumbnail}]
  1821. category = microformat.get('category') or search_meta('genre')
  1822. channel_id = video_details.get('channelId') \
  1823. or microformat.get('externalChannelId') \
  1824. or search_meta('channelId')
  1825. duration = int_or_none(
  1826. video_details.get('lengthSeconds')
  1827. or microformat.get('lengthSeconds')) \
  1828. or parse_duration(search_meta('duration'))
  1829. is_live = video_details.get('isLive')
  1830. owner_profile_url = microformat.get('ownerProfileUrl')
  1831. if not player_url:
  1832. player_url = self._extract_player_url(webpage)
  1833. self._unthrottle_format_urls(video_id, player_url, formats)
  1834. info = {
  1835. 'id': video_id,
  1836. 'title': self._live_title(video_title) if is_live else video_title,
  1837. 'formats': formats,
  1838. 'thumbnails': thumbnails,
  1839. 'description': video_description,
  1840. 'upload_date': unified_strdate(
  1841. microformat.get('uploadDate')
  1842. or search_meta('uploadDate')),
  1843. 'uploader': video_details['author'],
  1844. 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?&#]+)', owner_profile_url, 'uploader id') if owner_profile_url else None,
  1845. 'uploader_url': owner_profile_url,
  1846. 'channel_id': channel_id,
  1847. 'channel_url': 'https://www.youtube.com/channel/' + channel_id if channel_id else None,
  1848. 'duration': duration,
  1849. 'view_count': int_or_none(
  1850. video_details.get('viewCount')
  1851. or microformat.get('viewCount')
  1852. or search_meta('interactionCount')),
  1853. 'average_rating': float_or_none(video_details.get('averageRating')),
  1854. 'age_limit': 18 if (
  1855. microformat.get('isFamilySafe') is False
  1856. or search_meta('isFamilyFriendly') == 'false'
  1857. or search_meta('og:restrictions:age') == '18+') else 0,
  1858. 'webpage_url': webpage_url,
  1859. 'categories': [category] if category else None,
  1860. 'tags': keywords,
  1861. 'is_live': is_live,
  1862. }
  1863. pctr = try_get(
  1864. player_response,
  1865. lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict)
  1866. if pctr:
  1867. def process_language(container, base_url, lang_code, query):
  1868. lang_subs = []
  1869. for fmt in self._SUBTITLE_FORMATS:
  1870. query.update({
  1871. 'fmt': fmt,
  1872. })
  1873. lang_subs.append({
  1874. 'ext': fmt,
  1875. 'url': update_url_query(base_url, query),
  1876. })
  1877. container[lang_code] = lang_subs
  1878. subtitles = {}
  1879. for caption_track in (pctr.get('captionTracks') or []):
  1880. base_url = caption_track.get('baseUrl')
  1881. if not base_url:
  1882. continue
  1883. if caption_track.get('kind') != 'asr':
  1884. lang_code = caption_track.get('languageCode')
  1885. if not lang_code:
  1886. continue
  1887. process_language(
  1888. subtitles, base_url, lang_code, {})
  1889. continue
  1890. automatic_captions = {}
  1891. for translation_language in (pctr.get('translationLanguages') or []):
  1892. translation_language_code = translation_language.get('languageCode')
  1893. if not translation_language_code:
  1894. continue
  1895. process_language(
  1896. automatic_captions, base_url, translation_language_code,
  1897. {'tlang': translation_language_code})
  1898. info['automatic_captions'] = automatic_captions
  1899. info['subtitles'] = subtitles
  1900. parsed_url = compat_urllib_parse_urlparse(url)
  1901. for component in [parsed_url.fragment, parsed_url.query]:
  1902. query = compat_parse_qs(component)
  1903. for k, v in query.items():
  1904. for d_k, s_ks in [('start', ('start', 't')), ('end', ('end',))]:
  1905. d_k += '_time'
  1906. if d_k not in info and k in s_ks:
  1907. info[d_k] = parse_duration(query[k][0])
  1908. if video_description:
  1909. mobj = re.search(r'(?s)(?P<track>[^·\n]+)·(?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]+))?.+\nAuto-generated by YouTube\.\s*$', video_description)
  1910. if mobj:
  1911. release_year = mobj.group('release_year')
  1912. release_date = mobj.group('release_date')
  1913. if release_date:
  1914. release_date = release_date.replace('-', '')
  1915. if not release_year:
  1916. release_year = release_date[:4]
  1917. info.update({
  1918. 'album': mobj.group('album'.strip()),
  1919. 'artist': mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·')),
  1920. 'track': mobj.group('track').strip(),
  1921. 'release_date': release_date,
  1922. 'release_year': int_or_none(release_year),
  1923. })
  1924. initial_data = None
  1925. if webpage:
  1926. initial_data = self._extract_yt_initial_variable(
  1927. webpage, self._YT_INITIAL_DATA_RE, video_id,
  1928. 'yt initial data')
  1929. if not initial_data:
  1930. initial_data = self._call_api(
  1931. 'next', {'videoId': video_id}, video_id, fatal=False)
  1932. if initial_data:
  1933. chapters = self._extract_chapters_from_json(
  1934. initial_data, video_id, duration)
  1935. if not chapters:
  1936. for engagment_pannel in (initial_data.get('engagementPanels') or []):
  1937. contents = try_get(
  1938. engagment_pannel, lambda x: x['engagementPanelSectionListRenderer']['content']['macroMarkersListRenderer']['contents'],
  1939. list)
  1940. if not contents:
  1941. continue
  1942. def chapter_time(mmlir):
  1943. return parse_duration(
  1944. get_text(mmlir.get('timeDescription')))
  1945. chapters = []
  1946. for next_num, content in enumerate(contents, start=1):
  1947. mmlir = content.get('macroMarkersListItemRenderer') or {}
  1948. start_time = chapter_time(mmlir)
  1949. end_time = chapter_time(try_get(
  1950. contents, lambda x: x[next_num]['macroMarkersListItemRenderer'])) \
  1951. if next_num < len(contents) else duration
  1952. if start_time is None or end_time is None:
  1953. continue
  1954. chapters.append({
  1955. 'start_time': start_time,
  1956. 'end_time': end_time,
  1957. 'title': get_text(mmlir.get('title')),
  1958. })
  1959. if chapters:
  1960. break
  1961. if chapters:
  1962. info['chapters'] = chapters
  1963. contents = try_get(
  1964. initial_data,
  1965. lambda x: x['contents']['twoColumnWatchNextResults']['results']['results']['contents'],
  1966. list) or []
  1967. for content in contents:
  1968. vpir = content.get('videoPrimaryInfoRenderer')
  1969. if vpir:
  1970. stl = vpir.get('superTitleLink')
  1971. if stl:
  1972. stl = get_text(stl)
  1973. if try_get(
  1974. vpir,
  1975. lambda x: x['superTitleIcon']['iconType']) == 'LOCATION_PIN':
  1976. info['location'] = stl
  1977. else:
  1978. mobj = re.search(r'(.+?)\s*S(\d+)\s*•\s*E(\d+)', stl)
  1979. if mobj:
  1980. info.update({
  1981. 'series': mobj.group(1),
  1982. 'season_number': int(mobj.group(2)),
  1983. 'episode_number': int(mobj.group(3)),
  1984. })
  1985. for tlb in (try_get(
  1986. vpir,
  1987. lambda x: x['videoActions']['menuRenderer']['topLevelButtons'],
  1988. list) or []):
  1989. tbr = tlb.get('toggleButtonRenderer') or {}
  1990. for getter, regex in [(
  1991. lambda x: x['defaultText']['accessibility']['accessibilityData'],
  1992. r'(?P<count>[\d,]+)\s*(?P<type>(?:dis)?like)'), ([
  1993. lambda x: x['accessibility'],
  1994. lambda x: x['accessibilityData']['accessibilityData'],
  1995. ], r'(?P<type>(?:dis)?like) this video along with (?P<count>[\d,]+) other people')]:
  1996. label = (try_get(tbr, getter, dict) or {}).get('label')
  1997. if label:
  1998. mobj = re.match(regex, label)
  1999. if mobj:
  2000. info[mobj.group('type') + '_count'] = str_to_int(mobj.group('count'))
  2001. break
  2002. sbr_tooltip = try_get(
  2003. vpir, lambda x: x['sentimentBar']['sentimentBarRenderer']['tooltip'])
  2004. if sbr_tooltip:
  2005. like_count, dislike_count = sbr_tooltip.split(' / ')
  2006. info.update({
  2007. 'like_count': str_to_int(like_count),
  2008. 'dislike_count': str_to_int(dislike_count),
  2009. })
  2010. vsir = content.get('videoSecondaryInfoRenderer')
  2011. if vsir:
  2012. info['channel'] = get_text(try_get(
  2013. vsir,
  2014. lambda x: x['owner']['videoOwnerRenderer']['title'],
  2015. dict))
  2016. rows = try_get(
  2017. vsir,
  2018. lambda x: x['metadataRowContainer']['metadataRowContainerRenderer']['rows'],
  2019. list) or []
  2020. multiple_songs = False
  2021. for row in rows:
  2022. if try_get(row, lambda x: x['metadataRowRenderer']['hasDividerLine']) is True:
  2023. multiple_songs = True
  2024. break
  2025. for row in rows:
  2026. mrr = row.get('metadataRowRenderer') or {}
  2027. mrr_title = mrr.get('title')
  2028. if not mrr_title:
  2029. continue
  2030. mrr_title = get_text(mrr['title'])
  2031. mrr_contents_text = get_text(mrr['contents'][0])
  2032. if mrr_title == 'License':
  2033. info['license'] = mrr_contents_text
  2034. elif not multiple_songs:
  2035. if mrr_title == 'Album':
  2036. info['album'] = mrr_contents_text
  2037. elif mrr_title == 'Artist':
  2038. info['artist'] = mrr_contents_text
  2039. elif mrr_title == 'Song':
  2040. info['track'] = mrr_contents_text
  2041. for s_k, d_k in [('artist', 'creator'), ('track', 'alt_title')]:
  2042. v = info.get(s_k)
  2043. if v:
  2044. info[d_k] = v
  2045. self.mark_watched(video_id, player_response)
  2046. return info
  2047. class YoutubeTabIE(YoutubeBaseInfoExtractor):
  2048. IE_DESC = 'YouTube.com tab'
  2049. _VALID_URL = r'''(?x)
  2050. https?://
  2051. (?:\w+\.)?
  2052. (?:
  2053. youtube(?:kids)?\.com|
  2054. invidio\.us
  2055. )/
  2056. (?:
  2057. (?:channel|c|user|feed|hashtag)/|
  2058. (?:playlist|watch)\?.*?\blist=|
  2059. (?!(?:watch|embed|v|e|results)\b)
  2060. )
  2061. (?P<id>[^/?\#&]+)
  2062. '''
  2063. IE_NAME = 'youtube:tab'
  2064. _TESTS = [{
  2065. # Shorts
  2066. 'url': 'https://www.youtube.com/@SuperCooperShorts/shorts',
  2067. 'playlist_mincount': 5,
  2068. 'info_dict': {
  2069. 'description': 'Short clips from Super Cooper Sundays!',
  2070. 'id': 'UCKMA8kHZ8bPYpnMNaUSxfEQ',
  2071. 'title': 'Super Cooper Shorts - Shorts',
  2072. }
  2073. }, {
  2074. # Channel that does not have a Shorts tab. Test should just download videos on Home tab instead
  2075. 'url': 'https://www.youtube.com/@emergencyawesome/shorts',
  2076. 'info_dict': {
  2077. 'description': 'md5:592c080c06fef4de3c902c4a8eecd850',
  2078. 'id': 'UCDiFRMQWpcp8_KD4vwIVicw',
  2079. 'title': 'Emergency Awesome - Home',
  2080. },
  2081. 'playlist_mincount': 5,
  2082. }, {
  2083. # playlists, multipage
  2084. 'url': 'https://www.youtube.com/c/ИгорьКлейнер/playlists?view=1&flow=grid',
  2085. 'playlist_mincount': 94,
  2086. 'info_dict': {
  2087. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  2088. 'title': 'Игорь Клейнер - Playlists',
  2089. 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
  2090. },
  2091. }, {
  2092. # playlists, multipage, different order
  2093. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2094. 'playlist_mincount': 94,
  2095. 'info_dict': {
  2096. 'id': 'UCqj7Cz7revf5maW9g5pgNcg',
  2097. 'title': 'Игорь Клейнер - Playlists',
  2098. 'description': 'md5:be97ee0f14ee314f1f002cf187166ee2',
  2099. },
  2100. }, {
  2101. # playlists, series
  2102. 'url': 'https://www.youtube.com/c/3blue1brown/playlists?view=50&sort=dd&shelf_id=3',
  2103. 'playlist_mincount': 5,
  2104. 'info_dict': {
  2105. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  2106. 'title': '3Blue1Brown - Playlists',
  2107. 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
  2108. },
  2109. }, {
  2110. # playlists, singlepage
  2111. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2112. 'playlist_mincount': 4,
  2113. 'info_dict': {
  2114. 'id': 'UCAEtajcuhQ6an9WEzY9LEMQ',
  2115. 'title': 'ThirstForScience - Playlists',
  2116. 'description': 'md5:609399d937ea957b0f53cbffb747a14c',
  2117. }
  2118. }, {
  2119. 'url': 'https://www.youtube.com/c/ChristophLaimer/playlists',
  2120. 'only_matching': True,
  2121. }, {
  2122. # basic, single video playlist
  2123. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2124. 'info_dict': {
  2125. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2126. 'uploader': 'Sergey M.',
  2127. 'id': 'PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2128. 'title': 'youtube-dl public playlist',
  2129. },
  2130. 'playlist_count': 1,
  2131. }, {
  2132. # empty playlist
  2133. 'url': 'https://www.youtube.com/playlist?list=PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2134. 'info_dict': {
  2135. 'uploader_id': 'UCmlqkdCBesrv2Lak1mF_MxA',
  2136. 'uploader': 'Sergey M.',
  2137. 'id': 'PL4lCao7KL_QFodcLWhDpGCYnngnHtQ-Xf',
  2138. 'title': 'youtube-dl empty playlist',
  2139. },
  2140. 'playlist_count': 0,
  2141. }, {
  2142. # Home tab
  2143. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/featured',
  2144. 'info_dict': {
  2145. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2146. 'title': 'lex will - Home',
  2147. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2148. },
  2149. 'playlist_mincount': 2,
  2150. }, {
  2151. # Videos tab
  2152. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos',
  2153. 'info_dict': {
  2154. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2155. 'title': 'lex will - Videos',
  2156. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2157. },
  2158. 'playlist_mincount': 975,
  2159. }, {
  2160. # Videos tab, sorted by popular
  2161. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/videos?view=0&sort=p&flow=grid',
  2162. 'info_dict': {
  2163. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2164. 'title': 'lex will - Videos',
  2165. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2166. },
  2167. 'playlist_mincount': 199,
  2168. }, {
  2169. # Playlists tab
  2170. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/playlists',
  2171. 'info_dict': {
  2172. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2173. 'title': 'lex will - Playlists',
  2174. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2175. },
  2176. 'playlist_mincount': 17,
  2177. }, {
  2178. # Community tab
  2179. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/community',
  2180. 'info_dict': {
  2181. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2182. 'title': 'lex will - Community',
  2183. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2184. },
  2185. 'playlist_mincount': 18,
  2186. }, {
  2187. # Channels tab
  2188. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w/channels',
  2189. 'info_dict': {
  2190. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  2191. 'title': 'lex will - Channels',
  2192. 'description': 'md5:2163c5d0ff54ed5f598d6a7e6211e488',
  2193. },
  2194. 'playlist_mincount': 138,
  2195. }, {
  2196. 'url': 'https://invidio.us/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2197. 'only_matching': True,
  2198. }, {
  2199. 'url': 'https://www.youtubekids.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2200. 'only_matching': True,
  2201. }, {
  2202. 'url': 'https://music.youtube.com/channel/UCmlqkdCBesrv2Lak1mF_MxA',
  2203. 'only_matching': True,
  2204. }, {
  2205. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2206. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2207. 'info_dict': {
  2208. 'title': '29C3: Not my department',
  2209. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2210. 'uploader': 'Christiaan008',
  2211. 'uploader_id': 'UCEPzS1rYsrkqzSLNp76nrcg',
  2212. },
  2213. 'playlist_count': 96,
  2214. }, {
  2215. 'note': 'Large playlist',
  2216. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2217. 'info_dict': {
  2218. 'title': 'Uploads from Cauchemar',
  2219. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2220. 'uploader': 'Cauchemar',
  2221. 'uploader_id': 'UCBABnxM4Ar9ten8Mdjj1j0Q',
  2222. },
  2223. 'playlist_mincount': 1123,
  2224. }, {
  2225. # even larger playlist, 8832 videos
  2226. 'url': 'http://www.youtube.com/user/NASAgovVideo/videos',
  2227. 'only_matching': True,
  2228. }, {
  2229. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2230. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2231. 'info_dict': {
  2232. 'title': 'Uploads from Interstellar Movie',
  2233. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2234. 'uploader': 'Interstellar Movie',
  2235. 'uploader_id': 'UCXw-G3eDE9trcvY2sBMM_aA',
  2236. },
  2237. 'playlist_mincount': 21,
  2238. }, {
  2239. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2240. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2241. 'info_dict': {
  2242. 'title': 'Data Analysis with Dr Mike Pound',
  2243. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2244. 'uploader_id': 'UC9-y-6csu5WGm29I7JiwpnA',
  2245. 'uploader': 'Computerphile',
  2246. },
  2247. 'playlist_mincount': 11,
  2248. }, {
  2249. 'url': 'https://invidio.us/playlist?list=PL4lCao7KL_QFVb7Iudeipvc2BCavECqzc',
  2250. 'only_matching': True,
  2251. }, {
  2252. # Playlist URL that does not actually serve a playlist
  2253. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2254. 'info_dict': {
  2255. 'id': 'FqZTN594JQw',
  2256. 'ext': 'webm',
  2257. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2258. 'uploader': 'STREEM',
  2259. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2260. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2261. 'upload_date': '20150526',
  2262. 'license': 'Standard YouTube License',
  2263. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2264. 'categories': ['People & Blogs'],
  2265. 'tags': list,
  2266. 'view_count': int,
  2267. 'like_count': int,
  2268. 'dislike_count': int,
  2269. },
  2270. 'params': {
  2271. 'skip_download': True,
  2272. },
  2273. 'skip': 'This video is not available.',
  2274. 'add_ie': [YoutubeIE.ie_key()],
  2275. }, {
  2276. 'url': 'https://www.youtubekids.com/watch?v=Agk7R8I8o5U&list=PUZ6jURNr1WQZCNHF0ao-c0g',
  2277. 'only_matching': True,
  2278. }, {
  2279. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  2280. 'only_matching': True,
  2281. }, {
  2282. 'url': 'https://www.youtube.com/channel/UCoMdktPbSTixAyNGwb-UYkQ/live',
  2283. 'info_dict': {
  2284. 'id': '9Auq9mYxFEE',
  2285. 'ext': 'mp4',
  2286. 'title': 'Watch Sky News live',
  2287. 'uploader': 'Sky News',
  2288. 'uploader_id': 'skynews',
  2289. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/skynews',
  2290. 'upload_date': '20191102',
  2291. 'description': 'md5:78de4e1c2359d0ea3ed829678e38b662',
  2292. 'categories': ['News & Politics'],
  2293. 'tags': list,
  2294. 'like_count': int,
  2295. 'dislike_count': int,
  2296. },
  2297. 'params': {
  2298. 'skip_download': True,
  2299. },
  2300. }, {
  2301. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2302. 'info_dict': {
  2303. 'id': 'a48o2S1cPoo',
  2304. 'ext': 'mp4',
  2305. 'title': 'The Young Turks - Live Main Show',
  2306. 'uploader': 'The Young Turks',
  2307. 'uploader_id': 'TheYoungTurks',
  2308. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2309. 'upload_date': '20150715',
  2310. 'license': 'Standard YouTube License',
  2311. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2312. 'categories': ['News & Politics'],
  2313. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2314. 'like_count': int,
  2315. 'dislike_count': int,
  2316. },
  2317. 'params': {
  2318. 'skip_download': True,
  2319. },
  2320. 'only_matching': True,
  2321. }, {
  2322. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2323. 'only_matching': True,
  2324. }, {
  2325. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2326. 'only_matching': True,
  2327. }, {
  2328. 'url': 'https://www.youtube.com/feed/trending',
  2329. 'only_matching': True,
  2330. }, {
  2331. # needs auth
  2332. 'url': 'https://www.youtube.com/feed/library',
  2333. 'only_matching': True,
  2334. }, {
  2335. # needs auth
  2336. 'url': 'https://www.youtube.com/feed/history',
  2337. 'only_matching': True,
  2338. }, {
  2339. # needs auth
  2340. 'url': 'https://www.youtube.com/feed/subscriptions',
  2341. 'only_matching': True,
  2342. }, {
  2343. # needs auth
  2344. 'url': 'https://www.youtube.com/feed/watch_later',
  2345. 'only_matching': True,
  2346. }, {
  2347. # no longer available?
  2348. 'url': 'https://www.youtube.com/feed/recommended',
  2349. 'only_matching': True,
  2350. }, {
  2351. # inline playlist with not always working continuations
  2352. 'url': 'https://www.youtube.com/watch?v=UC6u0Tct-Fo&list=PL36D642111D65BE7C',
  2353. 'only_matching': True,
  2354. }, {
  2355. 'url': 'https://www.youtube.com/course?list=ECUl4u3cNGP61MdtwGTqZA0MreSaDybji8',
  2356. 'only_matching': True,
  2357. }, {
  2358. 'url': 'https://www.youtube.com/course',
  2359. 'only_matching': True,
  2360. }, {
  2361. 'url': 'https://www.youtube.com/zsecurity',
  2362. 'only_matching': True,
  2363. }, {
  2364. 'url': 'http://www.youtube.com/NASAgovVideo/videos',
  2365. 'only_matching': True,
  2366. }, {
  2367. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2368. 'only_matching': True,
  2369. }, {
  2370. 'url': 'https://www.youtube.com/hashtag/cctv9',
  2371. 'info_dict': {
  2372. 'id': 'cctv9',
  2373. 'title': '#cctv9',
  2374. },
  2375. 'playlist_mincount': 350,
  2376. }, {
  2377. 'url': 'https://www.youtube.com/watch?list=PLW4dVinRY435CBE_JD3t-0SRXKfnZHS1P&feature=youtu.be&v=M9cJMXmQ_ZU',
  2378. 'only_matching': True,
  2379. }, {
  2380. 'note': 'Search tab',
  2381. 'url': 'https://www.youtube.com/c/3blue1brown/search?query=linear%20algebra',
  2382. 'playlist_mincount': 40,
  2383. 'info_dict': {
  2384. 'id': 'UCYO_jab_esuFRV4b17AJtAw',
  2385. 'title': '3Blue1Brown - Search - linear algebra',
  2386. 'description': 'md5:e1384e8a133307dd10edee76e875d62f',
  2387. 'uploader': '3Blue1Brown',
  2388. 'uploader_id': 'UCYO_jab_esuFRV4b17AJtAw',
  2389. }
  2390. }]
  2391. @classmethod
  2392. def suitable(cls, url):
  2393. return False if YoutubeIE.suitable(url) else super(
  2394. YoutubeTabIE, cls).suitable(url)
  2395. def _extract_channel_id(self, webpage):
  2396. channel_id = self._html_search_meta(
  2397. 'channelId', webpage, 'channel id', default=None)
  2398. if channel_id:
  2399. return channel_id
  2400. channel_url = self._html_search_meta(
  2401. ('og:url', 'al:ios:url', 'al:android:url', 'al:web:url',
  2402. 'twitter:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad',
  2403. 'twitter:app:url:googleplay'), webpage, 'channel url')
  2404. return self._search_regex(
  2405. r'https?://(?:www\.)?youtube\.com/channel/([^/?#&])+',
  2406. channel_url, 'channel id')
  2407. @staticmethod
  2408. def _extract_grid_item_renderer(item):
  2409. assert isinstance(item, dict)
  2410. for key, renderer in item.items():
  2411. if not key.startswith('grid') or not key.endswith('Renderer'):
  2412. continue
  2413. if not isinstance(renderer, dict):
  2414. continue
  2415. return renderer
  2416. def _grid_entries(self, grid_renderer):
  2417. for item in grid_renderer['items']:
  2418. if not isinstance(item, dict):
  2419. continue
  2420. renderer = self._extract_grid_item_renderer(item)
  2421. if not isinstance(renderer, dict):
  2422. continue
  2423. title = try_get(
  2424. renderer, (lambda x: x['title']['runs'][0]['text'],
  2425. lambda x: x['title']['simpleText']), compat_str)
  2426. # playlist
  2427. playlist_id = renderer.get('playlistId')
  2428. if playlist_id:
  2429. yield self.url_result(
  2430. 'https://www.youtube.com/playlist?list=%s' % playlist_id,
  2431. ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  2432. video_title=title)
  2433. continue
  2434. # video
  2435. video_id = renderer.get('videoId')
  2436. if video_id:
  2437. yield self._extract_video(renderer)
  2438. continue
  2439. # channel
  2440. channel_id = renderer.get('channelId')
  2441. if channel_id:
  2442. title = try_get(
  2443. renderer, lambda x: x['title']['simpleText'], compat_str)
  2444. yield self.url_result(
  2445. 'https://www.youtube.com/channel/%s' % channel_id,
  2446. ie=YoutubeTabIE.ie_key(), video_title=title)
  2447. continue
  2448. # generic endpoint URL support
  2449. ep_url = urljoin('https://www.youtube.com/', try_get(
  2450. renderer, lambda x: x['navigationEndpoint']['commandMetadata']['webCommandMetadata']['url'],
  2451. compat_str))
  2452. if ep_url:
  2453. for ie in (YoutubeTabIE, YoutubePlaylistIE, YoutubeIE):
  2454. if ie.suitable(ep_url):
  2455. yield self.url_result(
  2456. ep_url, ie=ie.ie_key(), video_id=ie._match_id(ep_url), video_title=title)
  2457. break
  2458. def _shelf_entries_from_content(self, shelf_renderer):
  2459. content = shelf_renderer.get('content')
  2460. if not isinstance(content, dict):
  2461. return
  2462. renderer = content.get('gridRenderer')
  2463. if renderer:
  2464. # TODO: add support for nested playlists so each shelf is processed
  2465. # as separate playlist
  2466. # TODO: this includes only first N items
  2467. for entry in self._grid_entries(renderer):
  2468. yield entry
  2469. renderer = content.get('horizontalListRenderer')
  2470. if renderer:
  2471. # TODO
  2472. pass
  2473. def _shelf_entries(self, shelf_renderer, skip_channels=False):
  2474. ep = try_get(
  2475. shelf_renderer, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  2476. compat_str)
  2477. shelf_url = urljoin('https://www.youtube.com', ep)
  2478. if shelf_url:
  2479. # Skipping links to another channels, note that checking for
  2480. # endpoint.commandMetadata.webCommandMetadata.webPageTypwebPageType == WEB_PAGE_TYPE_CHANNEL
  2481. # will not work
  2482. if skip_channels and '/channels?' in shelf_url:
  2483. return
  2484. title = try_get(
  2485. shelf_renderer, lambda x: x['title']['runs'][0]['text'], compat_str)
  2486. yield self.url_result(shelf_url, video_title=title)
  2487. # Shelf may not contain shelf URL, fallback to extraction from content
  2488. for entry in self._shelf_entries_from_content(shelf_renderer):
  2489. yield entry
  2490. def _playlist_entries(self, video_list_renderer):
  2491. for content in video_list_renderer['contents']:
  2492. if not isinstance(content, dict):
  2493. continue
  2494. renderer = content.get('playlistVideoRenderer') or content.get('playlistPanelVideoRenderer')
  2495. if not isinstance(renderer, dict):
  2496. continue
  2497. video_id = renderer.get('videoId')
  2498. if not video_id:
  2499. continue
  2500. yield self._extract_video(renderer)
  2501. def _video_entry(self, video_renderer):
  2502. video_id = video_renderer.get('videoId')
  2503. if video_id:
  2504. return self._extract_video(video_renderer)
  2505. def _post_thread_entries(self, post_thread_renderer):
  2506. post_renderer = try_get(
  2507. post_thread_renderer, lambda x: x['post']['backstagePostRenderer'], dict)
  2508. if not post_renderer:
  2509. return
  2510. # video attachment
  2511. video_renderer = try_get(
  2512. post_renderer, lambda x: x['backstageAttachment']['videoRenderer'], dict)
  2513. video_id = None
  2514. if video_renderer:
  2515. entry = self._video_entry(video_renderer)
  2516. if entry:
  2517. yield entry
  2518. # inline video links
  2519. runs = try_get(post_renderer, lambda x: x['contentText']['runs'], list) or []
  2520. for run in runs:
  2521. if not isinstance(run, dict):
  2522. continue
  2523. ep_url = try_get(
  2524. run, lambda x: x['navigationEndpoint']['urlEndpoint']['url'], compat_str)
  2525. if not ep_url:
  2526. continue
  2527. if not YoutubeIE.suitable(ep_url):
  2528. continue
  2529. ep_video_id = YoutubeIE._match_id(ep_url)
  2530. if video_id == ep_video_id:
  2531. continue
  2532. yield self.url_result(ep_url, ie=YoutubeIE.ie_key(), video_id=video_id)
  2533. def _post_thread_continuation_entries(self, post_thread_continuation):
  2534. contents = post_thread_continuation.get('contents')
  2535. if not isinstance(contents, list):
  2536. return
  2537. for content in contents:
  2538. renderer = content.get('backstagePostThreadRenderer')
  2539. if not isinstance(renderer, dict):
  2540. continue
  2541. for entry in self._post_thread_entries(renderer):
  2542. yield entry
  2543. def _rich_grid_entries(self, contents):
  2544. for content in contents:
  2545. video_renderer = try_get(
  2546. content,
  2547. (lambda x: x['richItemRenderer']['content']['videoRenderer'],
  2548. lambda x: x['richItemRenderer']['content']['reelItemRenderer']),
  2549. dict)
  2550. if video_renderer:
  2551. entry = self._video_entry(video_renderer)
  2552. if entry:
  2553. yield entry
  2554. @staticmethod
  2555. def _build_continuation_query(continuation, ctp=None):
  2556. query = {
  2557. 'ctoken': continuation,
  2558. 'continuation': continuation,
  2559. }
  2560. if ctp:
  2561. query['itct'] = ctp
  2562. return query
  2563. @staticmethod
  2564. def _extract_next_continuation_data(renderer):
  2565. next_continuation = try_get(
  2566. renderer, lambda x: x['continuations'][0]['nextContinuationData'], dict)
  2567. if not next_continuation:
  2568. return
  2569. continuation = next_continuation.get('continuation')
  2570. if not continuation:
  2571. return
  2572. ctp = next_continuation.get('clickTrackingParams')
  2573. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  2574. @classmethod
  2575. def _extract_continuation(cls, renderer):
  2576. next_continuation = cls._extract_next_continuation_data(renderer)
  2577. if next_continuation:
  2578. return next_continuation
  2579. contents = []
  2580. for key in ('contents', 'items'):
  2581. contents.extend(try_get(renderer, lambda x: x[key], list) or [])
  2582. for content in contents:
  2583. if not isinstance(content, dict):
  2584. continue
  2585. continuation_ep = try_get(
  2586. content, lambda x: x['continuationItemRenderer']['continuationEndpoint'],
  2587. dict)
  2588. if not continuation_ep:
  2589. continue
  2590. continuation = try_get(
  2591. continuation_ep, lambda x: x['continuationCommand']['token'], compat_str)
  2592. if not continuation:
  2593. continue
  2594. ctp = continuation_ep.get('clickTrackingParams')
  2595. return YoutubeTabIE._build_continuation_query(continuation, ctp)
  2596. def _entries(self, tab, item_id, webpage):
  2597. tab_content = try_get(tab, lambda x: x['content'], dict)
  2598. if not tab_content:
  2599. return
  2600. slr_renderer = try_get(tab_content, lambda x: x['sectionListRenderer'], dict)
  2601. if slr_renderer:
  2602. is_channels_tab = tab.get('title') == 'Channels'
  2603. continuation = None
  2604. slr_contents = try_get(slr_renderer, lambda x: x['contents'], list) or []
  2605. for slr_content in slr_contents:
  2606. if not isinstance(slr_content, dict):
  2607. continue
  2608. is_renderer = try_get(slr_content, lambda x: x['itemSectionRenderer'], dict)
  2609. if not is_renderer:
  2610. continue
  2611. isr_contents = try_get(is_renderer, lambda x: x['contents'], list) or []
  2612. for isr_content in isr_contents:
  2613. if not isinstance(isr_content, dict):
  2614. continue
  2615. renderer = isr_content.get('playlistVideoListRenderer')
  2616. if renderer:
  2617. for entry in self._playlist_entries(renderer):
  2618. yield entry
  2619. continuation = self._extract_continuation(renderer)
  2620. continue
  2621. renderer = isr_content.get('gridRenderer')
  2622. if renderer:
  2623. for entry in self._grid_entries(renderer):
  2624. yield entry
  2625. continuation = self._extract_continuation(renderer)
  2626. continue
  2627. renderer = isr_content.get('shelfRenderer')
  2628. if renderer:
  2629. for entry in self._shelf_entries(renderer, not is_channels_tab):
  2630. yield entry
  2631. continue
  2632. renderer = isr_content.get('backstagePostThreadRenderer')
  2633. if renderer:
  2634. for entry in self._post_thread_entries(renderer):
  2635. yield entry
  2636. continuation = self._extract_continuation(renderer)
  2637. continue
  2638. renderer = isr_content.get('videoRenderer')
  2639. if renderer:
  2640. entry = self._video_entry(renderer)
  2641. if entry:
  2642. yield entry
  2643. if not continuation:
  2644. continuation = self._extract_continuation(is_renderer)
  2645. if not continuation:
  2646. continuation = self._extract_continuation(slr_renderer)
  2647. else:
  2648. rich_grid_renderer = tab_content.get('richGridRenderer')
  2649. if not rich_grid_renderer:
  2650. return
  2651. for entry in self._rich_grid_entries(rich_grid_renderer.get('contents') or []):
  2652. yield entry
  2653. continuation = self._extract_continuation(rich_grid_renderer)
  2654. ytcfg = self._extract_ytcfg(item_id, webpage)
  2655. client_version = try_get(
  2656. ytcfg, lambda x: x['INNERTUBE_CLIENT_VERSION'], compat_str) or '2.20210407.08.00'
  2657. headers = {
  2658. 'x-youtube-client-name': '1',
  2659. 'x-youtube-client-version': client_version,
  2660. 'content-type': 'application/json',
  2661. }
  2662. context = try_get(ytcfg, lambda x: x['INNERTUBE_CONTEXT'], dict) or {
  2663. 'client': {
  2664. 'clientName': 'WEB',
  2665. 'clientVersion': client_version,
  2666. }
  2667. }
  2668. visitor_data = try_get(context, lambda x: x['client']['visitorData'], compat_str)
  2669. identity_token = self._extract_identity_token(ytcfg, webpage)
  2670. if identity_token:
  2671. headers['x-youtube-identity-token'] = identity_token
  2672. data = {
  2673. 'context': context,
  2674. }
  2675. for page_num in itertools.count(1):
  2676. if not continuation:
  2677. break
  2678. if visitor_data:
  2679. headers['x-goog-visitor-id'] = visitor_data
  2680. data['continuation'] = continuation['continuation']
  2681. data['clickTracking'] = {
  2682. 'clickTrackingParams': continuation['itct']
  2683. }
  2684. count = 0
  2685. retries = 3
  2686. while count <= retries:
  2687. try:
  2688. # Downloading page may result in intermittent 5xx HTTP error
  2689. # that is usually worked around with a retry
  2690. response = self._download_json(
  2691. 'https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  2692. None, 'Downloading page %d%s' % (page_num, ' (retry #%d)' % count if count else ''),
  2693. headers=headers, data=json.dumps(data).encode('utf8'))
  2694. break
  2695. except ExtractorError as e:
  2696. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  2697. count += 1
  2698. if count <= retries:
  2699. continue
  2700. raise
  2701. if not response:
  2702. break
  2703. visitor_data = try_get(
  2704. response, lambda x: x['responseContext']['visitorData'], compat_str) or visitor_data
  2705. continuation_contents = try_get(
  2706. response, lambda x: x['continuationContents'], dict)
  2707. if continuation_contents:
  2708. continuation_renderer = continuation_contents.get('playlistVideoListContinuation')
  2709. if continuation_renderer:
  2710. for entry in self._playlist_entries(continuation_renderer):
  2711. yield entry
  2712. continuation = self._extract_continuation(continuation_renderer)
  2713. continue
  2714. continuation_renderer = continuation_contents.get('gridContinuation')
  2715. if continuation_renderer:
  2716. for entry in self._grid_entries(continuation_renderer):
  2717. yield entry
  2718. continuation = self._extract_continuation(continuation_renderer)
  2719. continue
  2720. continuation_renderer = continuation_contents.get('itemSectionContinuation')
  2721. if continuation_renderer:
  2722. for entry in self._post_thread_continuation_entries(continuation_renderer):
  2723. yield entry
  2724. continuation = self._extract_continuation(continuation_renderer)
  2725. continue
  2726. on_response_received = dict_get(response, ('onResponseReceivedActions', 'onResponseReceivedEndpoints'))
  2727. continuation_items = try_get(
  2728. on_response_received, lambda x: x[0]['appendContinuationItemsAction']['continuationItems'], list)
  2729. if continuation_items:
  2730. continuation_item = continuation_items[0]
  2731. if not isinstance(continuation_item, dict):
  2732. continue
  2733. renderer = self._extract_grid_item_renderer(continuation_item)
  2734. if renderer:
  2735. grid_renderer = {'items': continuation_items}
  2736. for entry in self._grid_entries(grid_renderer):
  2737. yield entry
  2738. continuation = self._extract_continuation(grid_renderer)
  2739. continue
  2740. renderer = continuation_item.get('playlistVideoRenderer') or continuation_item.get('itemSectionRenderer')
  2741. if renderer:
  2742. video_list_renderer = {'contents': continuation_items}
  2743. for entry in self._playlist_entries(video_list_renderer):
  2744. yield entry
  2745. continuation = self._extract_continuation(video_list_renderer)
  2746. continue
  2747. renderer = continuation_item.get('backstagePostThreadRenderer')
  2748. if renderer:
  2749. continuation_renderer = {'contents': continuation_items}
  2750. for entry in self._post_thread_continuation_entries(continuation_renderer):
  2751. yield entry
  2752. continuation = self._extract_continuation(continuation_renderer)
  2753. continue
  2754. renderer = continuation_item.get('richItemRenderer')
  2755. if renderer:
  2756. for entry in self._rich_grid_entries(continuation_items):
  2757. yield entry
  2758. continuation = self._extract_continuation({'contents': continuation_items})
  2759. continue
  2760. break
  2761. @staticmethod
  2762. def _extract_selected_tab(tabs):
  2763. for tab in tabs:
  2764. renderer = dict_get(tab, ('tabRenderer', 'expandableTabRenderer')) or {}
  2765. if renderer.get('selected') is True:
  2766. return renderer
  2767. else:
  2768. raise ExtractorError('Unable to find selected tab')
  2769. @staticmethod
  2770. def _extract_uploader(data):
  2771. uploader = {}
  2772. sidebar_renderer = try_get(
  2773. data, lambda x: x['sidebar']['playlistSidebarRenderer']['items'], list)
  2774. if sidebar_renderer:
  2775. for item in sidebar_renderer:
  2776. if not isinstance(item, dict):
  2777. continue
  2778. renderer = item.get('playlistSidebarSecondaryInfoRenderer')
  2779. if not isinstance(renderer, dict):
  2780. continue
  2781. owner = try_get(
  2782. renderer, lambda x: x['videoOwner']['videoOwnerRenderer']['title']['runs'][0], dict)
  2783. if owner:
  2784. uploader['uploader'] = owner.get('text')
  2785. uploader['uploader_id'] = try_get(
  2786. owner, lambda x: x['navigationEndpoint']['browseEndpoint']['browseId'], compat_str)
  2787. uploader['uploader_url'] = urljoin(
  2788. 'https://www.youtube.com/',
  2789. try_get(owner, lambda x: x['navigationEndpoint']['browseEndpoint']['canonicalBaseUrl'], compat_str))
  2790. return uploader
  2791. @staticmethod
  2792. def _extract_alert(data):
  2793. alerts = []
  2794. for alert in try_get(data, lambda x: x['alerts'], list) or []:
  2795. if not isinstance(alert, dict):
  2796. continue
  2797. alert_text = try_get(
  2798. alert, lambda x: x['alertRenderer']['text'], dict)
  2799. if not alert_text:
  2800. continue
  2801. text = try_get(
  2802. alert_text,
  2803. (lambda x: x['simpleText'], lambda x: x['runs'][0]['text']),
  2804. compat_str)
  2805. if text:
  2806. alerts.append(text)
  2807. return '\n'.join(alerts)
  2808. def _extract_from_tabs(self, item_id, webpage, data, tabs):
  2809. selected_tab = self._extract_selected_tab(tabs)
  2810. renderer = try_get(
  2811. data, lambda x: x['metadata']['channelMetadataRenderer'], dict)
  2812. playlist_id = item_id
  2813. title = description = None
  2814. if renderer:
  2815. channel_title = renderer.get('title') or item_id
  2816. tab_title = selected_tab.get('title')
  2817. title = channel_title or item_id
  2818. if tab_title:
  2819. title += ' - %s' % tab_title
  2820. if selected_tab.get('expandedText'):
  2821. title += ' - %s' % selected_tab['expandedText']
  2822. description = renderer.get('description')
  2823. playlist_id = renderer.get('externalId')
  2824. else:
  2825. renderer = try_get(
  2826. data, lambda x: x['metadata']['playlistMetadataRenderer'], dict)
  2827. if renderer:
  2828. title = renderer.get('title')
  2829. else:
  2830. renderer = try_get(
  2831. data, lambda x: x['header']['hashtagHeaderRenderer'], dict)
  2832. if renderer:
  2833. title = try_get(renderer, lambda x: x['hashtag']['simpleText'])
  2834. playlist = self.playlist_result(
  2835. self._entries(selected_tab, item_id, webpage),
  2836. playlist_id=playlist_id, playlist_title=title,
  2837. playlist_description=description)
  2838. playlist.update(self._extract_uploader(data))
  2839. return playlist
  2840. def _extract_from_playlist(self, item_id, url, data, playlist):
  2841. title = playlist.get('title') or try_get(
  2842. data, lambda x: x['titleText']['simpleText'], compat_str)
  2843. playlist_id = playlist.get('playlistId') or item_id
  2844. # Inline playlist rendition continuation does not always work
  2845. # at Youtube side, so delegating regular tab-based playlist URL
  2846. # processing whenever possible.
  2847. playlist_url = urljoin(url, try_get(
  2848. playlist, lambda x: x['endpoint']['commandMetadata']['webCommandMetadata']['url'],
  2849. compat_str))
  2850. if playlist_url and playlist_url != url:
  2851. return self.url_result(
  2852. playlist_url, ie=YoutubeTabIE.ie_key(), video_id=playlist_id,
  2853. video_title=title)
  2854. return self.playlist_result(
  2855. self._playlist_entries(playlist), playlist_id=playlist_id,
  2856. playlist_title=title)
  2857. def _extract_identity_token(self, ytcfg, webpage):
  2858. if ytcfg:
  2859. token = try_get(ytcfg, lambda x: x['ID_TOKEN'], compat_str)
  2860. if token:
  2861. return token
  2862. return self._search_regex(
  2863. r'\bID_TOKEN["\']\s*:\s*["\'](.+?)["\']', webpage,
  2864. 'identity token', default=None)
  2865. def _real_extract(self, url):
  2866. item_id = self._match_id(url)
  2867. url = compat_urlparse.urlunparse(
  2868. compat_urlparse.urlparse(url)._replace(netloc='www.youtube.com'))
  2869. # Handle both video/playlist URLs
  2870. qs = parse_qs(url)
  2871. video_id = qs.get('v', [None])[0]
  2872. playlist_id = qs.get('list', [None])[0]
  2873. if video_id and playlist_id:
  2874. if self._downloader.params.get('noplaylist'):
  2875. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2876. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  2877. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2878. webpage = self._download_webpage(url, item_id)
  2879. data = self._extract_yt_initial_data(item_id, webpage)
  2880. tabs = try_get(
  2881. data, lambda x: x['contents']['twoColumnBrowseResultsRenderer']['tabs'], list)
  2882. if tabs:
  2883. return self._extract_from_tabs(item_id, webpage, data, tabs)
  2884. playlist = try_get(
  2885. data, lambda x: x['contents']['twoColumnWatchNextResults']['playlist']['playlist'], dict)
  2886. if playlist:
  2887. return self._extract_from_playlist(item_id, url, data, playlist)
  2888. # Fallback to video extraction if no playlist alike page is recognized.
  2889. # First check for the current video then try the v attribute of URL query.
  2890. video_id = try_get(
  2891. data, lambda x: x['currentVideoEndpoint']['watchEndpoint']['videoId'],
  2892. compat_str) or video_id
  2893. if video_id:
  2894. return self.url_result(video_id, ie=YoutubeIE.ie_key(), video_id=video_id)
  2895. # Capture and output alerts
  2896. alert = self._extract_alert(data)
  2897. if alert:
  2898. raise ExtractorError(alert, expected=True)
  2899. # Failed to recognize
  2900. raise ExtractorError('Unable to recognize tab page')
  2901. class YoutubePlaylistIE(InfoExtractor):
  2902. IE_DESC = 'YouTube.com playlists'
  2903. _VALID_URL = r'''(?x)(?:
  2904. (?:https?://)?
  2905. (?:\w+\.)?
  2906. (?:
  2907. (?:
  2908. youtube(?:kids)?\.com|
  2909. invidio\.us
  2910. )
  2911. /.*?\?.*?\blist=
  2912. )?
  2913. (?P<id>%(playlist_id)s)
  2914. )''' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2915. IE_NAME = 'youtube:playlist'
  2916. _TESTS = [{
  2917. 'note': 'issue #673',
  2918. 'url': 'PLBB231211A4F62143',
  2919. 'info_dict': {
  2920. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2921. 'id': 'PLBB231211A4F62143',
  2922. 'uploader': 'Wickydoo',
  2923. 'uploader_id': 'UCKSpbfbl5kRQpTdL7kMc-1Q',
  2924. },
  2925. 'playlist_mincount': 29,
  2926. }, {
  2927. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2928. 'info_dict': {
  2929. 'title': 'YDL_safe_search',
  2930. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2931. },
  2932. 'playlist_count': 2,
  2933. 'skip': 'This playlist is private',
  2934. }, {
  2935. 'note': 'embedded',
  2936. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2937. 'playlist_count': 4,
  2938. 'info_dict': {
  2939. 'title': 'JODA15',
  2940. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2941. 'uploader': 'milan',
  2942. 'uploader_id': 'UCEI1-PVPcYXjB73Hfelbmaw',
  2943. }
  2944. }, {
  2945. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2946. 'playlist_mincount': 982,
  2947. 'info_dict': {
  2948. 'title': '2018 Chinese New Singles (11/6 updated)',
  2949. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2950. 'uploader': 'LBK',
  2951. 'uploader_id': 'UC21nz3_MesPLqtDqwdvnoxA',
  2952. }
  2953. }, {
  2954. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2955. 'only_matching': True,
  2956. }, {
  2957. # music album playlist
  2958. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2959. 'only_matching': True,
  2960. }]
  2961. @classmethod
  2962. def suitable(cls, url):
  2963. if YoutubeTabIE.suitable(url):
  2964. return False
  2965. # Hack for lazy extractors until more generic solution is implemented
  2966. # (see #28780)
  2967. from .youtube import parse_qs
  2968. qs = parse_qs(url)
  2969. if qs.get('v', [None])[0]:
  2970. return False
  2971. return super(YoutubePlaylistIE, cls).suitable(url)
  2972. def _real_extract(self, url):
  2973. playlist_id = self._match_id(url)
  2974. qs = parse_qs(url)
  2975. if not qs:
  2976. qs = {'list': playlist_id}
  2977. return self.url_result(
  2978. update_url_query('https://www.youtube.com/playlist', qs),
  2979. ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  2980. class YoutubeYtBeIE(InfoExtractor):
  2981. _VALID_URL = r'https?://youtu\.be/(?P<id>[0-9A-Za-z_-]{11})/*?.*?\blist=(?P<playlist_id>%(playlist_id)s)' % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2982. _TESTS = [{
  2983. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2984. 'info_dict': {
  2985. 'id': 'yeWKywCrFtk',
  2986. 'ext': 'mp4',
  2987. 'title': 'Small Scale Baler and Braiding Rugs',
  2988. 'uploader': 'Backus-Page House Museum',
  2989. 'uploader_id': 'backuspagemuseum',
  2990. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2991. 'upload_date': '20161008',
  2992. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2993. 'categories': ['Nonprofits & Activism'],
  2994. 'tags': list,
  2995. 'like_count': int,
  2996. 'dislike_count': int,
  2997. },
  2998. 'params': {
  2999. 'noplaylist': True,
  3000. 'skip_download': True,
  3001. },
  3002. }, {
  3003. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  3004. 'only_matching': True,
  3005. }]
  3006. def _real_extract(self, url):
  3007. mobj = re.match(self._VALID_URL, url)
  3008. video_id = mobj.group('id')
  3009. playlist_id = mobj.group('playlist_id')
  3010. return self.url_result(
  3011. update_url_query('https://www.youtube.com/watch', {
  3012. 'v': video_id,
  3013. 'list': playlist_id,
  3014. 'feature': 'youtu.be',
  3015. }), ie=YoutubeTabIE.ie_key(), video_id=playlist_id)
  3016. class YoutubeYtUserIE(InfoExtractor):
  3017. _VALID_URL = r'ytuser:(?P<id>.+)'
  3018. _TESTS = [{
  3019. 'url': 'ytuser:phihag',
  3020. 'only_matching': True,
  3021. }]
  3022. def _real_extract(self, url):
  3023. user_id = self._match_id(url)
  3024. return self.url_result(
  3025. 'https://www.youtube.com/user/%s' % user_id,
  3026. ie=YoutubeTabIE.ie_key(), video_id=user_id)
  3027. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  3028. IE_NAME = 'youtube:favorites'
  3029. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  3030. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  3031. _LOGIN_REQUIRED = True
  3032. _TESTS = [{
  3033. 'url': ':ytfav',
  3034. 'only_matching': True,
  3035. }, {
  3036. 'url': ':ytfavorites',
  3037. 'only_matching': True,
  3038. }]
  3039. def _real_extract(self, url):
  3040. return self.url_result(
  3041. 'https://www.youtube.com/playlist?list=LL',
  3042. ie=YoutubeTabIE.ie_key())
  3043. class YoutubeSearchIE(SearchInfoExtractor, YoutubeBaseInfoExtractor):
  3044. IE_DESC = 'YouTube.com searches'
  3045. IE_NAME = 'youtube:search'
  3046. _SEARCH_KEY = 'ytsearch'
  3047. _SEARCH_PARAMS = 'EgIQAQ%3D%3D' # Videos only
  3048. _MAX_RESULTS = float('inf')
  3049. _TESTS = [{
  3050. 'url': 'ytsearch10:youtube-dl test video',
  3051. 'playlist_count': 10,
  3052. 'info_dict': {
  3053. 'id': 'youtube-dl test video',
  3054. 'title': 'youtube-dl test video',
  3055. }
  3056. }]
  3057. def _get_n_results(self, query, n):
  3058. """Get a specified number of results for a query"""
  3059. entries = itertools.islice(self._search_results(query, self._SEARCH_PARAMS), 0, None if n == float('inf') else n)
  3060. return self.playlist_result(entries, query, query)
  3061. class YoutubeSearchDateIE(YoutubeSearchIE):
  3062. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  3063. _SEARCH_KEY = 'ytsearchdate'
  3064. IE_DESC = 'YouTube.com searches, newest videos first'
  3065. _SEARCH_PARAMS = 'CAISAhAB' # Videos only, sorted by date
  3066. _TESTS = [{
  3067. 'url': 'ytsearchdate10:youtube-dl test video',
  3068. 'playlist_count': 10,
  3069. 'info_dict': {
  3070. 'id': 'youtube-dl test video',
  3071. 'title': 'youtube-dl test video',
  3072. }
  3073. }]
  3074. class YoutubeSearchURLIE(YoutubeBaseInfoExtractor):
  3075. IE_DESC = 'YouTube search URLs with sorting and filter support'
  3076. IE_NAME = YoutubeSearchIE.IE_NAME + '_url'
  3077. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?:[^&]+)(?:[&]|$)'
  3078. _TESTS = [{
  3079. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  3080. 'playlist_mincount': 5,
  3081. 'info_dict': {
  3082. 'id': 'youtube-dl test video',
  3083. 'title': 'youtube-dl test video',
  3084. },
  3085. 'params': {'playlistend': 5}
  3086. }, {
  3087. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  3088. 'only_matching': True,
  3089. }]
  3090. def _real_extract(self, url):
  3091. qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  3092. query = (qs.get('search_query') or qs.get('q'))[0]
  3093. params = qs.get('sp', ('',))[0]
  3094. return self.playlist_result(self._search_results(query, params), query, query)
  3095. class YoutubeFeedsInfoExtractor(YoutubeTabIE):
  3096. """
  3097. Base class for feed extractors
  3098. Subclasses must define the _FEED_NAME property.
  3099. """
  3100. _LOGIN_REQUIRED = True
  3101. @property
  3102. def IE_NAME(self):
  3103. return 'youtube:%s' % self._FEED_NAME
  3104. def _real_initialize(self):
  3105. self._login()
  3106. def _real_extract(self, url):
  3107. return self.url_result(
  3108. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  3109. ie=YoutubeTabIE.ie_key())
  3110. class YoutubeWatchLaterIE(InfoExtractor):
  3111. IE_NAME = 'youtube:watchlater'
  3112. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  3113. _VALID_URL = r':ytwatchlater'
  3114. _TESTS = [{
  3115. 'url': ':ytwatchlater',
  3116. 'only_matching': True,
  3117. }]
  3118. def _real_extract(self, url):
  3119. return self.url_result(
  3120. 'https://www.youtube.com/playlist?list=WL', ie=YoutubeTabIE.ie_key())
  3121. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  3122. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  3123. _VALID_URL = r':ytrec(?:ommended)?'
  3124. _FEED_NAME = 'recommended'
  3125. _TESTS = [{
  3126. 'url': ':ytrec',
  3127. 'only_matching': True,
  3128. }, {
  3129. 'url': ':ytrecommended',
  3130. 'only_matching': True,
  3131. }]
  3132. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  3133. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  3134. _VALID_URL = r':ytsubs(?:criptions)?'
  3135. _FEED_NAME = 'subscriptions'
  3136. _TESTS = [{
  3137. 'url': ':ytsubs',
  3138. 'only_matching': True,
  3139. }, {
  3140. 'url': ':ytsubscriptions',
  3141. 'only_matching': True,
  3142. }]
  3143. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  3144. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  3145. _VALID_URL = r':ythistory'
  3146. _FEED_NAME = 'history'
  3147. _TESTS = [{
  3148. 'url': ':ythistory',
  3149. 'only_matching': True,
  3150. }]
  3151. class YoutubeTruncatedURLIE(InfoExtractor):
  3152. IE_NAME = 'youtube:truncated_url'
  3153. IE_DESC = False # Do not list
  3154. _VALID_URL = r'''(?x)
  3155. (?:https?://)?
  3156. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  3157. (?:watch\?(?:
  3158. feature=[a-z_]+|
  3159. annotation_id=annotation_[^&]+|
  3160. x-yt-cl=[0-9]+|
  3161. hl=[^&]*|
  3162. t=[0-9]+
  3163. )?
  3164. |
  3165. attribution_link\?a=[^&]+
  3166. )
  3167. $
  3168. '''
  3169. _TESTS = [{
  3170. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  3171. 'only_matching': True,
  3172. }, {
  3173. 'url': 'https://www.youtube.com/watch?',
  3174. 'only_matching': True,
  3175. }, {
  3176. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  3177. 'only_matching': True,
  3178. }, {
  3179. 'url': 'https://www.youtube.com/watch?feature=foo',
  3180. 'only_matching': True,
  3181. }, {
  3182. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  3183. 'only_matching': True,
  3184. }, {
  3185. 'url': 'https://www.youtube.com/watch?t=2372',
  3186. 'only_matching': True,
  3187. }]
  3188. def _real_extract(self, url):
  3189. raise ExtractorError(
  3190. 'Did you forget to quote the URL? Remember that & is a meta '
  3191. 'character in most shells, so you want to put the URL in quotes, '
  3192. 'like youtube-dl '
  3193. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  3194. ' or simply youtube-dl BaW_jenozKc .',
  3195. expected=True)
  3196. class YoutubeTruncatedIDIE(InfoExtractor):
  3197. IE_NAME = 'youtube:truncated_id'
  3198. IE_DESC = False # Do not list
  3199. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  3200. _TESTS = [{
  3201. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  3202. 'only_matching': True,
  3203. }]
  3204. def _real_extract(self, url):
  3205. video_id = self._match_id(url)
  3206. raise ExtractorError(
  3207. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  3208. expected=True)