youtube.py 130 KB

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