youtube.py 158 KB

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