youtube.py 155 KB

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