youtube.py 134 KB

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