youtube.py 156 KB

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