youtube.py 158 KB

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