youtube.py 132 KB

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