youtube.py 159 KB

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