youtube.py 132 KB

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