youtube.py 147 KB

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