youtube.py 138 KB

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