youtube.py 160 KB

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