youtube.py 151 KB

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