youtube.py 158 KB

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