youtube.py 159 KB

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