youtube.py 146 KB

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