youtube.py 144 KB

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