youtube.py 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. import os.path
  6. import re
  7. import time
  8. import traceback
  9. from .common import InfoExtractor, SearchInfoExtractor
  10. from ..jsinterp import JSInterpreter
  11. from ..swfinterp import SWFInterpreter
  12. from ..compat import (
  13. compat_chr,
  14. compat_parse_qs,
  15. compat_urllib_parse,
  16. compat_urllib_parse_unquote,
  17. compat_urllib_parse_unquote_plus,
  18. compat_urllib_parse_urlparse,
  19. compat_urlparse,
  20. compat_str,
  21. )
  22. from ..utils import (
  23. clean_html,
  24. encode_dict,
  25. ExtractorError,
  26. float_or_none,
  27. get_element_by_attribute,
  28. get_element_by_id,
  29. int_or_none,
  30. orderedSet,
  31. parse_duration,
  32. remove_start,
  33. sanitized_Request,
  34. smuggle_url,
  35. str_to_int,
  36. unescapeHTML,
  37. unified_strdate,
  38. unsmuggle_url,
  39. uppercase_escape,
  40. ISO3166Utils,
  41. )
  42. class YoutubeBaseInfoExtractor(InfoExtractor):
  43. """Provide base functions for Youtube extractors"""
  44. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  45. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  46. _NETRC_MACHINE = 'youtube'
  47. # If True it will raise an error if no login info is provided
  48. _LOGIN_REQUIRED = False
  49. def _set_language(self):
  50. self._set_cookie(
  51. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  52. # YouTube sets the expire time to about two months
  53. expire_time=time.time() + 2 * 30 * 24 * 3600)
  54. def _ids_to_results(self, ids):
  55. return [
  56. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  57. for vid_id in ids]
  58. def _login(self):
  59. """
  60. Attempt to log in to YouTube.
  61. True is returned if successful or skipped.
  62. False is returned if login failed.
  63. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  64. """
  65. (username, password) = self._get_login_info()
  66. # No authentication to be performed
  67. if username is None:
  68. if self._LOGIN_REQUIRED:
  69. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  70. return True
  71. login_page = self._download_webpage(
  72. self._LOGIN_URL, None,
  73. note='Downloading login page',
  74. errnote='unable to fetch login page', fatal=False)
  75. if login_page is False:
  76. return
  77. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  78. login_page, 'Login GALX parameter')
  79. # Log in
  80. login_form_strs = {
  81. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  82. 'Email': username,
  83. 'GALX': galx,
  84. 'Passwd': password,
  85. 'PersistentCookie': 'yes',
  86. '_utf8': '霱',
  87. 'bgresponse': 'js_disabled',
  88. 'checkConnection': '',
  89. 'checkedDomains': 'youtube',
  90. 'dnConn': '',
  91. 'pstMsg': '0',
  92. 'rmShown': '1',
  93. 'secTok': '',
  94. 'signIn': 'Sign in',
  95. 'timeStmp': '',
  96. 'service': 'youtube',
  97. 'uilel': '3',
  98. 'hl': 'en_US',
  99. }
  100. login_data = compat_urllib_parse.urlencode(encode_dict(login_form_strs)).encode('ascii')
  101. req = sanitized_Request(self._LOGIN_URL, login_data)
  102. login_results = self._download_webpage(
  103. req, None,
  104. note='Logging in', errnote='unable to log in', fatal=False)
  105. if login_results is False:
  106. return False
  107. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  108. raise ExtractorError('Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  109. # Two-Factor
  110. # TODO add SMS and phone call support - these require making a request and then prompting the user
  111. if re.search(r'(?i)<form[^>]* id="challenge"', login_results) is not None:
  112. tfa_code = self._get_tfa_info('2-step verification code')
  113. if not tfa_code:
  114. self._downloader.report_warning(
  115. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  116. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  117. return False
  118. tfa_code = remove_start(tfa_code, 'G-')
  119. tfa_form_strs = self._form_hidden_inputs('challenge', login_results)
  120. tfa_form_strs.update({
  121. 'Pin': tfa_code,
  122. 'TrustDevice': 'on',
  123. })
  124. tfa_data = compat_urllib_parse.urlencode(encode_dict(tfa_form_strs)).encode('ascii')
  125. tfa_req = sanitized_Request(self._TWOFACTOR_URL, tfa_data)
  126. tfa_results = self._download_webpage(
  127. tfa_req, None,
  128. note='Submitting TFA code', errnote='unable to submit tfa', fatal=False)
  129. if tfa_results is False:
  130. return False
  131. if re.search(r'(?i)<form[^>]* id="challenge"', tfa_results) is not None:
  132. self._downloader.report_warning('Two-factor code expired or invalid. Please try again, or use a one-use backup code instead.')
  133. return False
  134. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  135. self._downloader.report_warning('unable to log in - did the page structure change?')
  136. return False
  137. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  138. self._downloader.report_warning('Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  139. return False
  140. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  141. self._downloader.report_warning('unable to log in: bad username or password')
  142. return False
  143. return True
  144. def _real_initialize(self):
  145. if self._downloader is None:
  146. return
  147. self._set_language()
  148. if not self._login():
  149. return
  150. class YoutubeEntryListBaseInfoExtractor(InfoExtractor):
  151. # Extract entries from page with "Load more" button
  152. def _entries(self, page, playlist_id):
  153. more_widget_html = content_html = page
  154. for page_num in itertools.count(1):
  155. for entry in self._process_page(content_html):
  156. yield entry
  157. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  158. if not mobj:
  159. break
  160. more = self._download_json(
  161. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  162. 'Downloading page #%s' % page_num,
  163. transform_source=uppercase_escape)
  164. content_html = more['content_html']
  165. if not content_html.strip():
  166. # Some webpages show a "Load more" button but they don't
  167. # have more videos
  168. break
  169. more_widget_html = more['load_more_widget_html']
  170. class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  171. def _process_page(self, content):
  172. for video_id, video_title in self.extract_videos_from_page(content):
  173. yield self.url_result(video_id, 'Youtube', video_id, video_title)
  174. def extract_videos_from_page(self, page):
  175. ids_in_page = []
  176. titles_in_page = []
  177. for mobj in re.finditer(self._VIDEO_RE, page):
  178. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  179. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  180. continue
  181. video_id = mobj.group('id')
  182. video_title = unescapeHTML(mobj.group('title'))
  183. if video_title:
  184. video_title = video_title.strip()
  185. try:
  186. idx = ids_in_page.index(video_id)
  187. if video_title and not titles_in_page[idx]:
  188. titles_in_page[idx] = video_title
  189. except ValueError:
  190. ids_in_page.append(video_id)
  191. titles_in_page.append(video_title)
  192. return zip(ids_in_page, titles_in_page)
  193. class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  194. def _process_page(self, content):
  195. for playlist_id in re.findall(r'href="/?playlist\?list=(.+?)"', content):
  196. yield self.url_result(
  197. 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
  198. def _real_extract(self, url):
  199. playlist_id = self._match_id(url)
  200. webpage = self._download_webpage(url, playlist_id)
  201. title = self._og_search_title(webpage, fatal=False)
  202. return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
  203. class YoutubeIE(YoutubeBaseInfoExtractor):
  204. IE_DESC = 'YouTube.com'
  205. _VALID_URL = r"""(?x)^
  206. (
  207. (?:https?://|//) # http(s):// or protocol-independent URL
  208. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  209. (?:www\.)?deturl\.com/www\.youtube\.com/|
  210. (?:www\.)?pwnyoutube\.com/|
  211. (?:www\.)?yourepeat\.com/|
  212. tube\.majestyc\.net/|
  213. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  214. (?:.*?\#/)? # handle anchor (#/) redirect urls
  215. (?: # the various things that can precede the ID:
  216. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  217. |(?: # or the v= param in all its forms
  218. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  219. (?:\?|\#!?) # the params delimiter ? or # or #!
  220. (?:.*?&)?? # any other preceding param (like /?s=tuff&v=xxxx)
  221. v=
  222. )
  223. ))
  224. |(?:
  225. youtu\.be| # just youtu.be/xxxx
  226. vid\.plus # or vid.plus/xxxx
  227. )/
  228. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  229. )
  230. )? # all until now is optional -> you can pass the naked ID
  231. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  232. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  233. (?(1).+)? # if we found the ID, everything can follow
  234. $"""
  235. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  236. _formats = {
  237. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  238. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  239. '13': {'ext': '3gp'},
  240. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  241. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  242. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  243. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  244. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  245. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  246. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  247. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  248. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  249. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  250. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  251. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  252. '59': {'ext': 'mp4', 'width': 854, 'height': 480},
  253. '78': {'ext': 'mp4', 'width': 854, 'height': 480},
  254. # 3d videos
  255. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
  256. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
  257. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
  258. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
  259. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
  260. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
  261. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
  262. # Apple HTTP Live Streaming
  263. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  264. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
  265. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
  266. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
  267. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
  268. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  269. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
  270. # DASH mp4 video
  271. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  272. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  273. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  274. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  275. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  276. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, # Height can vary (https://github.com/rg3/youtube-dl/issues/4559)
  277. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  278. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  279. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'h264'},
  280. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'h264'},
  281. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'vcodec': 'h264'},
  282. # Dash mp4 audio
  283. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 48, 'preference': -50, 'container': 'm4a_dash'},
  284. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 128, 'preference': -50, 'container': 'm4a_dash'},
  285. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 256, 'preference': -50, 'container': 'm4a_dash'},
  286. # Dash webm
  287. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  288. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  289. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  290. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  291. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  292. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  293. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'container': 'webm', 'vcodec': 'vp9'},
  294. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  295. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  296. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  297. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  298. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  299. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  300. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  301. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  302. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  303. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  304. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  305. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  306. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'vcodec': 'vp9'},
  307. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  308. # Dash webm audio
  309. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  310. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  311. # Dash webm audio with opus inside
  312. '249': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50, 'preference': -50},
  313. '250': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70, 'preference': -50},
  314. '251': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160, 'preference': -50},
  315. # RTMP (unnamed)
  316. '_rtmp': {'protocol': 'rtmp'},
  317. }
  318. IE_NAME = 'youtube'
  319. _TESTS = [
  320. {
  321. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKcj&t=1s&end=9',
  322. 'info_dict': {
  323. 'id': 'BaW_jenozKc',
  324. 'ext': 'mp4',
  325. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  326. 'uploader': 'Philipp Hagemeister',
  327. 'uploader_id': 'phihag',
  328. 'upload_date': '20121002',
  329. '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 .',
  330. 'categories': ['Science & Technology'],
  331. 'tags': ['youtube-dl'],
  332. 'like_count': int,
  333. 'dislike_count': int,
  334. 'start_time': 1,
  335. 'end_time': 9,
  336. }
  337. },
  338. {
  339. 'url': 'http://www.youtube.com/watch?v=UxxajLWwzqY',
  340. 'note': 'Test generic use_cipher_signature video (#897)',
  341. 'info_dict': {
  342. 'id': 'UxxajLWwzqY',
  343. 'ext': 'mp4',
  344. 'upload_date': '20120506',
  345. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  346. 'description': 'md5:782e8651347686cba06e58f71ab51773',
  347. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  348. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  349. 'iconic ep', 'iconic', 'love', 'it'],
  350. 'uploader': 'Icona Pop',
  351. 'uploader_id': 'IconaPop',
  352. }
  353. },
  354. {
  355. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  356. 'note': 'Test VEVO video with age protection (#956)',
  357. 'info_dict': {
  358. 'id': '07FYdnEawAQ',
  359. 'ext': 'mp4',
  360. 'upload_date': '20130703',
  361. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  362. 'description': 'md5:64249768eec3bc4276236606ea996373',
  363. 'uploader': 'justintimberlakeVEVO',
  364. 'uploader_id': 'justintimberlakeVEVO',
  365. 'age_limit': 18,
  366. }
  367. },
  368. {
  369. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  370. 'note': 'Embed-only video (#1746)',
  371. 'info_dict': {
  372. 'id': 'yZIXLfi8CZQ',
  373. 'ext': 'mp4',
  374. 'upload_date': '20120608',
  375. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  376. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  377. 'uploader': 'SET India',
  378. 'uploader_id': 'setindia',
  379. 'age_limit': 18,
  380. }
  381. },
  382. {
  383. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKcj&v=UxxajLWwzqY',
  384. 'note': 'Use the first video ID in the URL',
  385. 'info_dict': {
  386. 'id': 'BaW_jenozKc',
  387. 'ext': 'mp4',
  388. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  389. 'uploader': 'Philipp Hagemeister',
  390. 'uploader_id': 'phihag',
  391. 'upload_date': '20121002',
  392. '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 .',
  393. 'categories': ['Science & Technology'],
  394. 'tags': ['youtube-dl'],
  395. 'like_count': int,
  396. 'dislike_count': int,
  397. },
  398. 'params': {
  399. 'skip_download': True,
  400. },
  401. },
  402. {
  403. 'url': 'http://www.youtube.com/watch?v=a9LDPn-MO4I',
  404. 'note': '256k DASH audio (format 141) via DASH manifest',
  405. 'info_dict': {
  406. 'id': 'a9LDPn-MO4I',
  407. 'ext': 'm4a',
  408. 'upload_date': '20121002',
  409. 'uploader_id': '8KVIDEO',
  410. 'description': '',
  411. 'uploader': '8KVIDEO',
  412. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  413. },
  414. 'params': {
  415. 'youtube_include_dash_manifest': True,
  416. 'format': '141',
  417. },
  418. },
  419. # DASH manifest with encrypted signature
  420. {
  421. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  422. 'info_dict': {
  423. 'id': 'IB3lcPjvWLA',
  424. 'ext': 'm4a',
  425. 'title': 'Afrojack, Spree Wilson - The Spark ft. Spree Wilson',
  426. 'description': 'md5:12e7067fa6735a77bdcbb58cb1187d2d',
  427. 'uploader': 'AfrojackVEVO',
  428. 'uploader_id': 'AfrojackVEVO',
  429. 'upload_date': '20131011',
  430. },
  431. 'params': {
  432. 'youtube_include_dash_manifest': True,
  433. 'format': '141',
  434. },
  435. },
  436. # JS player signature function name containing $
  437. {
  438. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  439. 'info_dict': {
  440. 'id': 'nfWlot6h_JM',
  441. 'ext': 'm4a',
  442. 'title': 'Taylor Swift - Shake It Off',
  443. 'description': 'md5:95f66187cd7c8b2c13eb78e1223b63c3',
  444. 'uploader': 'TaylorSwiftVEVO',
  445. 'uploader_id': 'TaylorSwiftVEVO',
  446. 'upload_date': '20140818',
  447. },
  448. 'params': {
  449. 'youtube_include_dash_manifest': True,
  450. 'format': '141',
  451. },
  452. },
  453. # Controversy video
  454. {
  455. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  456. 'info_dict': {
  457. 'id': 'T4XJQO3qol8',
  458. 'ext': 'mp4',
  459. 'upload_date': '20100909',
  460. 'uploader': 'The Amazing Atheist',
  461. 'uploader_id': 'TheAmazingAtheist',
  462. 'title': 'Burning Everyone\'s Koran',
  463. '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',
  464. }
  465. },
  466. # Normal age-gate video (No vevo, embed allowed)
  467. {
  468. 'url': 'http://youtube.com/watch?v=HtVdAasjOgU',
  469. 'info_dict': {
  470. 'id': 'HtVdAasjOgU',
  471. 'ext': 'mp4',
  472. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  473. 'description': 're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  474. 'uploader': 'The Witcher',
  475. 'uploader_id': 'WitcherGame',
  476. 'upload_date': '20140605',
  477. 'age_limit': 18,
  478. },
  479. },
  480. # Age-gate video with encrypted signature
  481. {
  482. 'url': 'http://www.youtube.com/watch?v=6kLq3WMV1nU',
  483. 'info_dict': {
  484. 'id': '6kLq3WMV1nU',
  485. 'ext': 'mp4',
  486. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  487. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  488. 'uploader': 'LloydVEVO',
  489. 'uploader_id': 'LloydVEVO',
  490. 'upload_date': '20110629',
  491. 'age_limit': 18,
  492. },
  493. },
  494. # video_info is None (https://github.com/rg3/youtube-dl/issues/4421)
  495. {
  496. 'url': '__2ABJjxzNo',
  497. 'info_dict': {
  498. 'id': '__2ABJjxzNo',
  499. 'ext': 'mp4',
  500. 'upload_date': '20100430',
  501. 'uploader_id': 'deadmau5',
  502. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  503. 'uploader': 'deadmau5',
  504. 'title': 'Deadmau5 - Some Chords (HD)',
  505. },
  506. 'expected_warnings': [
  507. 'DASH manifest missing',
  508. ]
  509. },
  510. # Olympics (https://github.com/rg3/youtube-dl/issues/4431)
  511. {
  512. 'url': 'lqQg6PlCWgI',
  513. 'info_dict': {
  514. 'id': 'lqQg6PlCWgI',
  515. 'ext': 'mp4',
  516. 'upload_date': '20150827',
  517. 'uploader_id': 'olympic',
  518. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  519. 'uploader': 'Olympics',
  520. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  521. },
  522. 'params': {
  523. 'skip_download': 'requires avconv',
  524. }
  525. },
  526. # Non-square pixels
  527. {
  528. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  529. 'info_dict': {
  530. 'id': '_b-2C3KPAM0',
  531. 'ext': 'mp4',
  532. 'stretched_ratio': 16 / 9.,
  533. 'upload_date': '20110310',
  534. 'uploader_id': 'AllenMeow',
  535. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  536. 'uploader': '孫艾倫',
  537. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  538. },
  539. },
  540. # url_encoded_fmt_stream_map is empty string
  541. {
  542. 'url': 'qEJwOuvDf7I',
  543. 'info_dict': {
  544. 'id': 'qEJwOuvDf7I',
  545. 'ext': 'webm',
  546. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  547. 'description': '',
  548. 'upload_date': '20150404',
  549. 'uploader_id': 'spbelect',
  550. 'uploader': 'Наблюдатели Петербурга',
  551. },
  552. 'params': {
  553. 'skip_download': 'requires avconv',
  554. }
  555. },
  556. # Extraction from multiple DASH manifests (https://github.com/rg3/youtube-dl/pull/6097)
  557. {
  558. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  559. 'info_dict': {
  560. 'id': 'FIl7x6_3R5Y',
  561. 'ext': 'mp4',
  562. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  563. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  564. 'upload_date': '20150625',
  565. 'uploader_id': 'dorappi2000',
  566. 'uploader': 'dorappi2000',
  567. 'formats': 'mincount:33',
  568. },
  569. },
  570. # DASH manifest with segment_list
  571. {
  572. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  573. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  574. 'info_dict': {
  575. 'id': 'CsmdDsKjzN8',
  576. 'ext': 'mp4',
  577. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  578. 'uploader': 'Airtek',
  579. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  580. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  581. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  582. },
  583. 'params': {
  584. 'youtube_include_dash_manifest': True,
  585. 'format': '135', # bestvideo
  586. }
  587. },
  588. {
  589. # Multifeed videos (multiple cameras), URL is for Main Camera
  590. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  591. 'info_dict': {
  592. 'id': 'jqWvoWXjCVs',
  593. 'title': 'teamPGP: Rocket League Noob Stream',
  594. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  595. },
  596. 'playlist': [{
  597. 'info_dict': {
  598. 'id': 'jqWvoWXjCVs',
  599. 'ext': 'mp4',
  600. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  601. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  602. 'upload_date': '20150721',
  603. 'uploader': 'Beer Games Beer',
  604. 'uploader_id': 'beergamesbeer',
  605. },
  606. }, {
  607. 'info_dict': {
  608. 'id': '6h8e8xoXJzg',
  609. 'ext': 'mp4',
  610. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  611. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  612. 'upload_date': '20150721',
  613. 'uploader': 'Beer Games Beer',
  614. 'uploader_id': 'beergamesbeer',
  615. },
  616. }, {
  617. 'info_dict': {
  618. 'id': 'PUOgX5z9xZw',
  619. 'ext': 'mp4',
  620. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  621. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  622. 'upload_date': '20150721',
  623. 'uploader': 'Beer Games Beer',
  624. 'uploader_id': 'beergamesbeer',
  625. },
  626. }, {
  627. 'info_dict': {
  628. 'id': 'teuwxikvS5k',
  629. 'ext': 'mp4',
  630. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  631. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  632. 'upload_date': '20150721',
  633. 'uploader': 'Beer Games Beer',
  634. 'uploader_id': 'beergamesbeer',
  635. },
  636. }],
  637. 'params': {
  638. 'skip_download': True,
  639. },
  640. },
  641. {
  642. 'url': 'http://vid.plus/FlRa-iH7PGw',
  643. 'only_matching': True,
  644. },
  645. {
  646. # Title with JS-like syntax "};" (see https://github.com/rg3/youtube-dl/issues/7468)
  647. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  648. 'info_dict': {
  649. 'id': 'lsguqyKfVQg',
  650. 'ext': 'mp4',
  651. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  652. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  653. 'upload_date': '20151119',
  654. 'uploader_id': 'IronSoulElf',
  655. 'uploader': 'IronSoulElf',
  656. },
  657. 'params': {
  658. 'skip_download': True,
  659. },
  660. },
  661. {
  662. # Tags with '};' (see https://github.com/rg3/youtube-dl/issues/7468)
  663. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  664. 'only_matching': True,
  665. },
  666. {
  667. # Video with yt:stretch=17:0
  668. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  669. 'info_dict': {
  670. 'id': 'Q39EVAstoRM',
  671. 'ext': 'mp4',
  672. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  673. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  674. 'upload_date': '20151107',
  675. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  676. 'uploader': 'CH GAMER DROID',
  677. },
  678. 'params': {
  679. 'skip_download': True,
  680. },
  681. },
  682. ]
  683. def __init__(self, *args, **kwargs):
  684. super(YoutubeIE, self).__init__(*args, **kwargs)
  685. self._player_cache = {}
  686. def report_video_info_webpage_download(self, video_id):
  687. """Report attempt to download video info webpage."""
  688. self.to_screen('%s: Downloading video info webpage' % video_id)
  689. def report_information_extraction(self, video_id):
  690. """Report attempt to extract video information."""
  691. self.to_screen('%s: Extracting video information' % video_id)
  692. def report_unavailable_format(self, video_id, format):
  693. """Report extracted video URL."""
  694. self.to_screen('%s: Format %s not available' % (video_id, format))
  695. def report_rtmp_download(self):
  696. """Indicate the download will use the RTMP protocol."""
  697. self.to_screen('RTMP download detected')
  698. def _signature_cache_id(self, example_sig):
  699. """ Return a string representation of a signature """
  700. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  701. def _extract_signature_function(self, video_id, player_url, example_sig):
  702. id_m = re.match(
  703. r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player(?:-new)?|/base)?\.(?P<ext>[a-z]+)$',
  704. player_url)
  705. if not id_m:
  706. raise ExtractorError('Cannot identify player %r' % player_url)
  707. player_type = id_m.group('ext')
  708. player_id = id_m.group('id')
  709. # Read from filesystem cache
  710. func_id = '%s_%s_%s' % (
  711. player_type, player_id, self._signature_cache_id(example_sig))
  712. assert os.path.basename(func_id) == func_id
  713. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  714. if cache_spec is not None:
  715. return lambda s: ''.join(s[i] for i in cache_spec)
  716. download_note = (
  717. 'Downloading player %s' % player_url
  718. if self._downloader.params.get('verbose') else
  719. 'Downloading %s player %s' % (player_type, player_id)
  720. )
  721. if player_type == 'js':
  722. code = self._download_webpage(
  723. player_url, video_id,
  724. note=download_note,
  725. errnote='Download of %s failed' % player_url)
  726. res = self._parse_sig_js(code)
  727. elif player_type == 'swf':
  728. urlh = self._request_webpage(
  729. player_url, video_id,
  730. note=download_note,
  731. errnote='Download of %s failed' % player_url)
  732. code = urlh.read()
  733. res = self._parse_sig_swf(code)
  734. else:
  735. assert False, 'Invalid player type %r' % player_type
  736. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  737. cache_res = res(test_string)
  738. cache_spec = [ord(c) for c in cache_res]
  739. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  740. return res
  741. def _print_sig_code(self, func, example_sig):
  742. def gen_sig_code(idxs):
  743. def _genslice(start, end, step):
  744. starts = '' if start == 0 else str(start)
  745. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  746. steps = '' if step == 1 else (':%d' % step)
  747. return 's[%s%s%s]' % (starts, ends, steps)
  748. step = None
  749. # Quelch pyflakes warnings - start will be set when step is set
  750. start = '(Never used)'
  751. for i, prev in zip(idxs[1:], idxs[:-1]):
  752. if step is not None:
  753. if i - prev == step:
  754. continue
  755. yield _genslice(start, prev, step)
  756. step = None
  757. continue
  758. if i - prev in [-1, 1]:
  759. step = i - prev
  760. start = prev
  761. continue
  762. else:
  763. yield 's[%d]' % prev
  764. if step is None:
  765. yield 's[%d]' % i
  766. else:
  767. yield _genslice(start, i, step)
  768. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  769. cache_res = func(test_string)
  770. cache_spec = [ord(c) for c in cache_res]
  771. expr_code = ' + '.join(gen_sig_code(cache_spec))
  772. signature_id_tuple = '(%s)' % (
  773. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  774. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  775. ' return %s\n') % (signature_id_tuple, expr_code)
  776. self.to_screen('Extracted signature function:\n' + code)
  777. def _parse_sig_js(self, jscode):
  778. funcname = self._search_regex(
  779. r'\.sig\|\|([a-zA-Z0-9$]+)\(', jscode,
  780. 'Initial JS player signature function name')
  781. jsi = JSInterpreter(jscode)
  782. initial_function = jsi.extract_function(funcname)
  783. return lambda s: initial_function([s])
  784. def _parse_sig_swf(self, file_contents):
  785. swfi = SWFInterpreter(file_contents)
  786. TARGET_CLASSNAME = 'SignatureDecipher'
  787. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  788. initial_function = swfi.extract_function(searched_class, 'decipher')
  789. return lambda s: initial_function([s])
  790. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  791. """Turn the encrypted s field into a working signature"""
  792. if player_url is None:
  793. raise ExtractorError('Cannot decrypt signature without player_url')
  794. if player_url.startswith('//'):
  795. player_url = 'https:' + player_url
  796. try:
  797. player_id = (player_url, self._signature_cache_id(s))
  798. if player_id not in self._player_cache:
  799. func = self._extract_signature_function(
  800. video_id, player_url, s
  801. )
  802. self._player_cache[player_id] = func
  803. func = self._player_cache[player_id]
  804. if self._downloader.params.get('youtube_print_sig_code'):
  805. self._print_sig_code(func, s)
  806. return func(s)
  807. except Exception as e:
  808. tb = traceback.format_exc()
  809. raise ExtractorError(
  810. 'Signature extraction failed: ' + tb, cause=e)
  811. def _get_subtitles(self, video_id, webpage):
  812. try:
  813. subs_doc = self._download_xml(
  814. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  815. video_id, note=False)
  816. except ExtractorError as err:
  817. self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
  818. return {}
  819. sub_lang_list = {}
  820. for track in subs_doc.findall('track'):
  821. lang = track.attrib['lang_code']
  822. if lang in sub_lang_list:
  823. continue
  824. sub_formats = []
  825. for ext in ['sbv', 'vtt', 'srt']:
  826. params = compat_urllib_parse.urlencode({
  827. 'lang': lang,
  828. 'v': video_id,
  829. 'fmt': ext,
  830. 'name': track.attrib['name'].encode('utf-8'),
  831. })
  832. sub_formats.append({
  833. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  834. 'ext': ext,
  835. })
  836. sub_lang_list[lang] = sub_formats
  837. if not sub_lang_list:
  838. self._downloader.report_warning('video doesn\'t have subtitles')
  839. return {}
  840. return sub_lang_list
  841. def _get_ytplayer_config(self, video_id, webpage):
  842. patterns = (
  843. # User data may contain arbitrary character sequences that may affect
  844. # JSON extraction with regex, e.g. when '};' is contained the second
  845. # regex won't capture the whole JSON. Yet working around by trying more
  846. # concrete regex first keeping in mind proper quoted string handling
  847. # to be implemented in future that will replace this workaround (see
  848. # https://github.com/rg3/youtube-dl/issues/7468,
  849. # https://github.com/rg3/youtube-dl/pull/7599)
  850. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  851. r';ytplayer\.config\s*=\s*({.+?});',
  852. )
  853. config = self._search_regex(
  854. patterns, webpage, 'ytplayer.config', default=None)
  855. if config:
  856. return self._parse_json(
  857. uppercase_escape(config), video_id, fatal=False)
  858. def _get_automatic_captions(self, video_id, webpage):
  859. """We need the webpage for getting the captions url, pass it as an
  860. argument to speed up the process."""
  861. self.to_screen('%s: Looking for automatic captions' % video_id)
  862. player_config = self._get_ytplayer_config(video_id, webpage)
  863. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  864. if not player_config:
  865. self._downloader.report_warning(err_msg)
  866. return {}
  867. try:
  868. args = player_config['args']
  869. caption_url = args['ttsurl']
  870. timestamp = args['timestamp']
  871. # We get the available subtitles
  872. list_params = compat_urllib_parse.urlencode({
  873. 'type': 'list',
  874. 'tlangs': 1,
  875. 'asrs': 1,
  876. })
  877. list_url = caption_url + '&' + list_params
  878. caption_list = self._download_xml(list_url, video_id)
  879. original_lang_node = caption_list.find('track')
  880. if original_lang_node is None:
  881. self._downloader.report_warning('Video doesn\'t have automatic captions')
  882. return {}
  883. original_lang = original_lang_node.attrib['lang_code']
  884. caption_kind = original_lang_node.attrib.get('kind', '')
  885. sub_lang_list = {}
  886. for lang_node in caption_list.findall('target'):
  887. sub_lang = lang_node.attrib['lang_code']
  888. sub_formats = []
  889. for ext in ['sbv', 'vtt', 'srt']:
  890. params = compat_urllib_parse.urlencode({
  891. 'lang': original_lang,
  892. 'tlang': sub_lang,
  893. 'fmt': ext,
  894. 'ts': timestamp,
  895. 'kind': caption_kind,
  896. })
  897. sub_formats.append({
  898. 'url': caption_url + '&' + params,
  899. 'ext': ext,
  900. })
  901. sub_lang_list[sub_lang] = sub_formats
  902. return sub_lang_list
  903. # An extractor error can be raise by the download process if there are
  904. # no automatic captions but there are subtitles
  905. except (KeyError, ExtractorError):
  906. self._downloader.report_warning(err_msg)
  907. return {}
  908. @classmethod
  909. def extract_id(cls, url):
  910. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  911. if mobj is None:
  912. raise ExtractorError('Invalid URL: %s' % url)
  913. video_id = mobj.group(2)
  914. return video_id
  915. def _extract_from_m3u8(self, manifest_url, video_id):
  916. url_map = {}
  917. def _get_urls(_manifest):
  918. lines = _manifest.split('\n')
  919. urls = filter(lambda l: l and not l.startswith('#'),
  920. lines)
  921. return urls
  922. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  923. formats_urls = _get_urls(manifest)
  924. for format_url in formats_urls:
  925. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  926. url_map[itag] = format_url
  927. return url_map
  928. def _extract_annotations(self, video_id):
  929. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  930. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  931. def _parse_dash_manifest(
  932. self, video_id, dash_manifest_url, player_url, age_gate, fatal=True):
  933. def decrypt_sig(mobj):
  934. s = mobj.group(1)
  935. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  936. return '/signature/%s' % dec_s
  937. dash_manifest_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, dash_manifest_url)
  938. dash_doc = self._download_xml(
  939. dash_manifest_url, video_id,
  940. note='Downloading DASH manifest',
  941. errnote='Could not download DASH manifest',
  942. fatal=fatal)
  943. if dash_doc is False:
  944. return []
  945. formats = []
  946. for a in dash_doc.findall('.//{urn:mpeg:DASH:schema:MPD:2011}AdaptationSet'):
  947. mime_type = a.attrib.get('mimeType')
  948. for r in a.findall('{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  949. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  950. if url_el is None:
  951. continue
  952. if mime_type == 'text/vtt':
  953. # TODO implement WebVTT downloading
  954. pass
  955. elif mime_type.startswith('audio/') or mime_type.startswith('video/'):
  956. segment_list = r.find('{urn:mpeg:DASH:schema:MPD:2011}SegmentList')
  957. format_id = r.attrib['id']
  958. video_url = url_el.text
  959. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  960. f = {
  961. 'format_id': format_id,
  962. 'url': video_url,
  963. 'width': int_or_none(r.attrib.get('width')),
  964. 'height': int_or_none(r.attrib.get('height')),
  965. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  966. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  967. 'filesize': filesize,
  968. 'fps': int_or_none(r.attrib.get('frameRate')),
  969. }
  970. if segment_list is not None:
  971. f.update({
  972. 'initialization_url': segment_list.find('{urn:mpeg:DASH:schema:MPD:2011}Initialization').attrib['sourceURL'],
  973. 'segment_urls': [segment.attrib.get('media') for segment in segment_list.findall('{urn:mpeg:DASH:schema:MPD:2011}SegmentURL')],
  974. 'protocol': 'http_dash_segments',
  975. })
  976. try:
  977. existing_format = next(
  978. fo for fo in formats
  979. if fo['format_id'] == format_id)
  980. except StopIteration:
  981. full_info = self._formats.get(format_id, {}).copy()
  982. full_info.update(f)
  983. codecs = r.attrib.get('codecs')
  984. if codecs:
  985. if full_info.get('acodec') == 'none' and 'vcodec' not in full_info:
  986. full_info['vcodec'] = codecs
  987. elif full_info.get('vcodec') == 'none' and 'acodec' not in full_info:
  988. full_info['acodec'] = codecs
  989. formats.append(full_info)
  990. else:
  991. existing_format.update(f)
  992. else:
  993. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  994. return formats
  995. def _real_extract(self, url):
  996. url, smuggled_data = unsmuggle_url(url, {})
  997. proto = (
  998. 'http' if self._downloader.params.get('prefer_insecure', False)
  999. else 'https')
  1000. start_time = None
  1001. end_time = None
  1002. parsed_url = compat_urllib_parse_urlparse(url)
  1003. for component in [parsed_url.fragment, parsed_url.query]:
  1004. query = compat_parse_qs(component)
  1005. if start_time is None and 't' in query:
  1006. start_time = parse_duration(query['t'][0])
  1007. if start_time is None and 'start' in query:
  1008. start_time = parse_duration(query['start'][0])
  1009. if end_time is None and 'end' in query:
  1010. end_time = parse_duration(query['end'][0])
  1011. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1012. mobj = re.search(self._NEXT_URL_RE, url)
  1013. if mobj:
  1014. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1015. video_id = self.extract_id(url)
  1016. # Get video webpage
  1017. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1018. video_webpage = self._download_webpage(url, video_id)
  1019. # Attempt to extract SWF player URL
  1020. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1021. if mobj is not None:
  1022. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1023. else:
  1024. player_url = None
  1025. dash_mpds = []
  1026. def add_dash_mpd(video_info):
  1027. dash_mpd = video_info.get('dashmpd')
  1028. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1029. dash_mpds.append(dash_mpd[0])
  1030. # Get video info
  1031. embed_webpage = None
  1032. is_live = None
  1033. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1034. age_gate = True
  1035. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1036. # this can be viewed without login into Youtube
  1037. url = proto + '://www.youtube.com/embed/%s' % video_id
  1038. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1039. data = compat_urllib_parse.urlencode({
  1040. 'video_id': video_id,
  1041. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1042. 'sts': self._search_regex(
  1043. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1044. })
  1045. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1046. video_info_webpage = self._download_webpage(
  1047. video_info_url, video_id,
  1048. note='Refetching age-gated info webpage',
  1049. errnote='unable to download video info webpage')
  1050. video_info = compat_parse_qs(video_info_webpage)
  1051. add_dash_mpd(video_info)
  1052. else:
  1053. age_gate = False
  1054. video_info = None
  1055. # Try looking directly into the video webpage
  1056. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1057. if ytplayer_config:
  1058. args = ytplayer_config['args']
  1059. if args.get('url_encoded_fmt_stream_map'):
  1060. # Convert to the same format returned by compat_parse_qs
  1061. video_info = dict((k, [v]) for k, v in args.items())
  1062. add_dash_mpd(video_info)
  1063. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1064. is_live = True
  1065. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1066. # We also try looking in get_video_info since it may contain different dashmpd
  1067. # URL that points to a DASH manifest with possibly different itag set (some itags
  1068. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1069. # manifest pointed by get_video_info's dashmpd).
  1070. # The general idea is to take a union of itags of both DASH manifests (for example
  1071. # video with such 'manifest behavior' see https://github.com/rg3/youtube-dl/issues/6093)
  1072. self.report_video_info_webpage_download(video_id)
  1073. for el_type in ['&el=info', '&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1074. video_info_url = (
  1075. '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1076. % (proto, video_id, el_type))
  1077. video_info_webpage = self._download_webpage(
  1078. video_info_url,
  1079. video_id, note=False,
  1080. errnote='unable to download video info webpage')
  1081. get_video_info = compat_parse_qs(video_info_webpage)
  1082. if get_video_info.get('use_cipher_signature') != ['True']:
  1083. add_dash_mpd(get_video_info)
  1084. if not video_info:
  1085. video_info = get_video_info
  1086. if 'token' in get_video_info:
  1087. # Different get_video_info requests may report different results, e.g.
  1088. # some may report video unavailability, but some may serve it without
  1089. # any complaint (see https://github.com/rg3/youtube-dl/issues/7362,
  1090. # the original webpage as well as el=info and el=embedded get_video_info
  1091. # requests report video unavailability due to geo restriction while
  1092. # el=detailpage succeeds and returns valid data). This is probably
  1093. # due to YouTube measures against IP ranges of hosting providers.
  1094. # Working around by preferring the first succeeded video_info containing
  1095. # the token if no such video_info yet was found.
  1096. if 'token' not in video_info:
  1097. video_info = get_video_info
  1098. break
  1099. if 'token' not in video_info:
  1100. if 'reason' in video_info:
  1101. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  1102. regions_allowed = self._html_search_meta('regionsAllowed', video_webpage, default=None)
  1103. if regions_allowed:
  1104. raise ExtractorError('YouTube said: This video is available in %s only' % (
  1105. ', '.join(map(ISO3166Utils.short2full, regions_allowed.split(',')))),
  1106. expected=True)
  1107. raise ExtractorError(
  1108. 'YouTube said: %s' % video_info['reason'][0],
  1109. expected=True, video_id=video_id)
  1110. else:
  1111. raise ExtractorError(
  1112. '"token" parameter not in video info for unknown reason',
  1113. video_id=video_id)
  1114. # title
  1115. if 'title' in video_info:
  1116. video_title = video_info['title'][0]
  1117. else:
  1118. self._downloader.report_warning('Unable to extract video title')
  1119. video_title = '_'
  1120. # description
  1121. video_description = get_element_by_id("eow-description", video_webpage)
  1122. if video_description:
  1123. video_description = re.sub(r'''(?x)
  1124. <a\s+
  1125. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1126. title="([^"]+)"\s+
  1127. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1128. class="yt-uix-redirect-link"\s*>
  1129. [^<]+
  1130. </a>
  1131. ''', r'\1', video_description)
  1132. video_description = clean_html(video_description)
  1133. else:
  1134. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1135. if fd_mobj:
  1136. video_description = unescapeHTML(fd_mobj.group(1))
  1137. else:
  1138. video_description = ''
  1139. if 'multifeed_metadata_list' in video_info and not smuggled_data.get('force_singlefeed', False):
  1140. if not self._downloader.params.get('noplaylist'):
  1141. entries = []
  1142. feed_ids = []
  1143. multifeed_metadata_list = compat_urllib_parse_unquote_plus(video_info['multifeed_metadata_list'][0])
  1144. for feed in multifeed_metadata_list.split(','):
  1145. feed_data = compat_parse_qs(feed)
  1146. entries.append({
  1147. '_type': 'url_transparent',
  1148. 'ie_key': 'Youtube',
  1149. 'url': smuggle_url(
  1150. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1151. {'force_singlefeed': True}),
  1152. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1153. })
  1154. feed_ids.append(feed_data['id'][0])
  1155. self.to_screen(
  1156. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1157. % (', '.join(feed_ids), video_id))
  1158. return self.playlist_result(entries, video_id, video_title, video_description)
  1159. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1160. if 'view_count' in video_info:
  1161. view_count = int(video_info['view_count'][0])
  1162. else:
  1163. view_count = None
  1164. # Check for "rental" videos
  1165. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1166. raise ExtractorError('"rental" videos not supported')
  1167. # Start extracting information
  1168. self.report_information_extraction(video_id)
  1169. # uploader
  1170. if 'author' not in video_info:
  1171. raise ExtractorError('Unable to extract uploader name')
  1172. video_uploader = compat_urllib_parse_unquote_plus(video_info['author'][0])
  1173. # uploader_id
  1174. video_uploader_id = None
  1175. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1176. if mobj is not None:
  1177. video_uploader_id = mobj.group(1)
  1178. else:
  1179. self._downloader.report_warning('unable to extract uploader nickname')
  1180. # thumbnail image
  1181. # We try first to get a high quality image:
  1182. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1183. video_webpage, re.DOTALL)
  1184. if m_thumb is not None:
  1185. video_thumbnail = m_thumb.group(1)
  1186. elif 'thumbnail_url' not in video_info:
  1187. self._downloader.report_warning('unable to extract video thumbnail')
  1188. video_thumbnail = None
  1189. else: # don't panic if we can't find it
  1190. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  1191. # upload date
  1192. upload_date = self._html_search_meta(
  1193. 'datePublished', video_webpage, 'upload date', default=None)
  1194. if not upload_date:
  1195. upload_date = self._search_regex(
  1196. [r'(?s)id="eow-date.*?>(.*?)</span>',
  1197. r'id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live|Started) on (.+?)</strong>'],
  1198. video_webpage, 'upload date', default=None)
  1199. if upload_date:
  1200. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1201. upload_date = unified_strdate(upload_date)
  1202. m_cat_container = self._search_regex(
  1203. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  1204. video_webpage, 'categories', default=None)
  1205. if m_cat_container:
  1206. category = self._html_search_regex(
  1207. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1208. default=None)
  1209. video_categories = None if category is None else [category]
  1210. else:
  1211. video_categories = None
  1212. video_tags = [
  1213. unescapeHTML(m.group('content'))
  1214. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  1215. def _extract_count(count_name):
  1216. return str_to_int(self._search_regex(
  1217. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  1218. % re.escape(count_name),
  1219. video_webpage, count_name, default=None))
  1220. like_count = _extract_count('like')
  1221. dislike_count = _extract_count('dislike')
  1222. # subtitles
  1223. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1224. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  1225. if 'length_seconds' not in video_info:
  1226. self._downloader.report_warning('unable to extract video duration')
  1227. video_duration = None
  1228. else:
  1229. video_duration = int(compat_urllib_parse_unquote_plus(video_info['length_seconds'][0]))
  1230. # annotations
  1231. video_annotations = None
  1232. if self._downloader.params.get('writeannotations', False):
  1233. video_annotations = self._extract_annotations(video_id)
  1234. def _map_to_format_list(urlmap):
  1235. formats = []
  1236. for itag, video_real_url in urlmap.items():
  1237. dct = {
  1238. 'format_id': itag,
  1239. 'url': video_real_url,
  1240. 'player_url': player_url,
  1241. }
  1242. if itag in self._formats:
  1243. dct.update(self._formats[itag])
  1244. formats.append(dct)
  1245. return formats
  1246. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1247. self.report_rtmp_download()
  1248. formats = [{
  1249. 'format_id': '_rtmp',
  1250. 'protocol': 'rtmp',
  1251. 'url': video_info['conn'][0],
  1252. 'player_url': player_url,
  1253. }]
  1254. elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
  1255. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1256. if 'rtmpe%3Dyes' in encoded_url_map:
  1257. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1258. formats = []
  1259. for url_data_str in encoded_url_map.split(','):
  1260. url_data = compat_parse_qs(url_data_str)
  1261. if 'itag' not in url_data or 'url' not in url_data:
  1262. continue
  1263. format_id = url_data['itag'][0]
  1264. url = url_data['url'][0]
  1265. if 'sig' in url_data:
  1266. url += '&signature=' + url_data['sig'][0]
  1267. elif 's' in url_data:
  1268. encrypted_sig = url_data['s'][0]
  1269. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1270. jsplayer_url_json = self._search_regex(
  1271. ASSETS_RE,
  1272. embed_webpage if age_gate else video_webpage,
  1273. 'JS player URL (1)', default=None)
  1274. if not jsplayer_url_json and not age_gate:
  1275. # We need the embed website after all
  1276. if embed_webpage is None:
  1277. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1278. embed_webpage = self._download_webpage(
  1279. embed_url, video_id, 'Downloading embed webpage')
  1280. jsplayer_url_json = self._search_regex(
  1281. ASSETS_RE, embed_webpage, 'JS player URL')
  1282. player_url = json.loads(jsplayer_url_json)
  1283. if player_url is None:
  1284. player_url_json = self._search_regex(
  1285. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1286. video_webpage, 'age gate player URL')
  1287. player_url = json.loads(player_url_json)
  1288. if self._downloader.params.get('verbose'):
  1289. if player_url is None:
  1290. player_version = 'unknown'
  1291. player_desc = 'unknown'
  1292. else:
  1293. if player_url.endswith('swf'):
  1294. player_version = self._search_regex(
  1295. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1296. 'flash player', fatal=False)
  1297. player_desc = 'flash player %s' % player_version
  1298. else:
  1299. player_version = self._search_regex(
  1300. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js', r'(?:www|player)-([^/]+)/base\.js'],
  1301. player_url,
  1302. 'html5 player', fatal=False)
  1303. player_desc = 'html5 player %s' % player_version
  1304. parts_sizes = self._signature_cache_id(encrypted_sig)
  1305. self.to_screen('{%s} signature length %s, %s' %
  1306. (format_id, parts_sizes, player_desc))
  1307. signature = self._decrypt_signature(
  1308. encrypted_sig, video_id, player_url, age_gate)
  1309. url += '&signature=' + signature
  1310. if 'ratebypass' not in url:
  1311. url += '&ratebypass=yes'
  1312. # Some itags are not included in DASH manifest thus corresponding formats will
  1313. # lack metadata (see https://github.com/rg3/youtube-dl/pull/5993).
  1314. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1315. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1316. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1317. dct = {
  1318. 'format_id': format_id,
  1319. 'url': url,
  1320. 'player_url': player_url,
  1321. 'filesize': int_or_none(url_data.get('clen', [None])[0]),
  1322. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1323. 'width': width,
  1324. 'height': height,
  1325. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1326. 'format_note': url_data.get('quality_label', [None])[0] or url_data.get('quality', [None])[0],
  1327. }
  1328. type_ = url_data.get('type', [None])[0]
  1329. if type_:
  1330. type_split = type_.split(';')
  1331. kind_ext = type_split[0].split('/')
  1332. if len(kind_ext) == 2:
  1333. kind, ext = kind_ext
  1334. dct['ext'] = ext
  1335. if kind in ('audio', 'video'):
  1336. codecs = None
  1337. for mobj in re.finditer(
  1338. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1339. if mobj.group('key') == 'codecs':
  1340. codecs = mobj.group('val')
  1341. break
  1342. if codecs:
  1343. codecs = codecs.split(',')
  1344. if len(codecs) == 2:
  1345. acodec, vcodec = codecs[0], codecs[1]
  1346. else:
  1347. acodec, vcodec = (codecs[0], 'none') if kind == 'audio' else ('none', codecs[0])
  1348. dct.update({
  1349. 'acodec': acodec,
  1350. 'vcodec': vcodec,
  1351. })
  1352. if format_id in self._formats:
  1353. dct.update(self._formats[format_id])
  1354. formats.append(dct)
  1355. elif video_info.get('hlsvp'):
  1356. manifest_url = video_info['hlsvp'][0]
  1357. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1358. formats = _map_to_format_list(url_map)
  1359. else:
  1360. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1361. # Look for the DASH manifest
  1362. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1363. dash_mpd_fatal = True
  1364. for dash_manifest_url in dash_mpds:
  1365. dash_formats = {}
  1366. try:
  1367. for df in self._parse_dash_manifest(
  1368. video_id, dash_manifest_url, player_url, age_gate, dash_mpd_fatal):
  1369. # Do not overwrite DASH format found in some previous DASH manifest
  1370. if df['format_id'] not in dash_formats:
  1371. dash_formats[df['format_id']] = df
  1372. # Additional DASH manifests may end up in HTTP Error 403 therefore
  1373. # allow them to fail without bug report message if we already have
  1374. # some DASH manifest succeeded. This is temporary workaround to reduce
  1375. # burst of bug reports until we figure out the reason and whether it
  1376. # can be fixed at all.
  1377. dash_mpd_fatal = False
  1378. except (ExtractorError, KeyError) as e:
  1379. self.report_warning(
  1380. 'Skipping DASH manifest: %r' % e, video_id)
  1381. if dash_formats:
  1382. # Remove the formats we found through non-DASH, they
  1383. # contain less info and it can be wrong, because we use
  1384. # fixed values (for example the resolution). See
  1385. # https://github.com/rg3/youtube-dl/issues/5774 for an
  1386. # example.
  1387. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  1388. formats.extend(dash_formats.values())
  1389. # Check for malformed aspect ratio
  1390. stretched_m = re.search(
  1391. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  1392. video_webpage)
  1393. if stretched_m:
  1394. w = float(stretched_m.group('w'))
  1395. h = float(stretched_m.group('h'))
  1396. if w > 0 and h > 0:
  1397. ratio = w / h
  1398. for f in formats:
  1399. if f.get('vcodec') != 'none':
  1400. f['stretched_ratio'] = ratio
  1401. self._sort_formats(formats)
  1402. return {
  1403. 'id': video_id,
  1404. 'uploader': video_uploader,
  1405. 'uploader_id': video_uploader_id,
  1406. 'upload_date': upload_date,
  1407. 'title': video_title,
  1408. 'thumbnail': video_thumbnail,
  1409. 'description': video_description,
  1410. 'categories': video_categories,
  1411. 'tags': video_tags,
  1412. 'subtitles': video_subtitles,
  1413. 'automatic_captions': automatic_captions,
  1414. 'duration': video_duration,
  1415. 'age_limit': 18 if age_gate else 0,
  1416. 'annotations': video_annotations,
  1417. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1418. 'view_count': view_count,
  1419. 'like_count': like_count,
  1420. 'dislike_count': dislike_count,
  1421. 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
  1422. 'formats': formats,
  1423. 'is_live': is_live,
  1424. 'start_time': start_time,
  1425. 'end_time': end_time,
  1426. }
  1427. class YoutubePlaylistIE(YoutubeBaseInfoExtractor, YoutubePlaylistBaseInfoExtractor):
  1428. IE_DESC = 'YouTube.com playlists'
  1429. _VALID_URL = r"""(?x)(?:
  1430. (?:https?://)?
  1431. (?:\w+\.)?
  1432. youtube\.com/
  1433. (?:
  1434. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  1435. \? (?:.*?&)*? (?:p|a|list)=
  1436. | p/
  1437. )
  1438. (
  1439. (?:PL|LL|EC|UU|FL|RD|UL)?[0-9A-Za-z-_]{10,}
  1440. # Top tracks, they can also include dots
  1441. |(?:MC)[\w\.]*
  1442. )
  1443. .*
  1444. |
  1445. ((?:PL|LL|EC|UU|FL|RD|UL)[0-9A-Za-z-_]{10,})
  1446. )"""
  1447. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1448. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
  1449. IE_NAME = 'youtube:playlist'
  1450. _TESTS = [{
  1451. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1452. 'info_dict': {
  1453. 'title': 'ytdl test PL',
  1454. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1455. },
  1456. 'playlist_count': 3,
  1457. }, {
  1458. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1459. 'info_dict': {
  1460. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1461. 'title': 'YDL_Empty_List',
  1462. },
  1463. 'playlist_count': 0,
  1464. }, {
  1465. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  1466. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1467. 'info_dict': {
  1468. 'title': '29C3: Not my department',
  1469. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1470. },
  1471. 'playlist_count': 95,
  1472. }, {
  1473. 'note': 'issue #673',
  1474. 'url': 'PLBB231211A4F62143',
  1475. 'info_dict': {
  1476. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  1477. 'id': 'PLBB231211A4F62143',
  1478. },
  1479. 'playlist_mincount': 26,
  1480. }, {
  1481. 'note': 'Large playlist',
  1482. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  1483. 'info_dict': {
  1484. 'title': 'Uploads from Cauchemar',
  1485. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  1486. },
  1487. 'playlist_mincount': 799,
  1488. }, {
  1489. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1490. 'info_dict': {
  1491. 'title': 'YDL_safe_search',
  1492. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1493. },
  1494. 'playlist_count': 2,
  1495. }, {
  1496. 'note': 'embedded',
  1497. 'url': 'http://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1498. 'playlist_count': 4,
  1499. 'info_dict': {
  1500. 'title': 'JODA15',
  1501. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1502. }
  1503. }, {
  1504. 'note': 'Embedded SWF player',
  1505. 'url': 'http://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  1506. 'playlist_count': 4,
  1507. 'info_dict': {
  1508. 'title': 'JODA7',
  1509. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  1510. }
  1511. }, {
  1512. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  1513. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  1514. 'info_dict': {
  1515. 'title': 'Uploads from Interstellar Movie',
  1516. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  1517. },
  1518. 'playlist_mincout': 21,
  1519. }]
  1520. def _real_initialize(self):
  1521. self._login()
  1522. def _extract_mix(self, playlist_id):
  1523. # The mixes are generated from a single video
  1524. # the id of the playlist is just 'RD' + video_id
  1525. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1526. webpage = self._download_webpage(
  1527. url, playlist_id, 'Downloading Youtube mix')
  1528. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1529. title_span = (
  1530. search_title('playlist-title') or
  1531. search_title('title long-title') or
  1532. search_title('title'))
  1533. title = clean_html(title_span)
  1534. ids = orderedSet(re.findall(
  1535. r'''(?xs)data-video-username=".*?".*?
  1536. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  1537. webpage))
  1538. url_results = self._ids_to_results(ids)
  1539. return self.playlist_result(url_results, playlist_id, title)
  1540. def _extract_playlist(self, playlist_id):
  1541. url = self._TEMPLATE_URL % playlist_id
  1542. page = self._download_webpage(url, playlist_id)
  1543. for match in re.findall(r'<div class="yt-alert-message">([^<]+)</div>', page):
  1544. match = match.strip()
  1545. # Check if the playlist exists or is private
  1546. if re.match(r'[^<]*(The|This) playlist (does not exist|is private)[^<]*', match):
  1547. raise ExtractorError(
  1548. 'The playlist doesn\'t exist or is private, use --username or '
  1549. '--netrc to access it.',
  1550. expected=True)
  1551. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  1552. raise ExtractorError(
  1553. 'Invalid parameters. Maybe URL is incorrect.',
  1554. expected=True)
  1555. elif re.match(r'[^<]*Choose your language[^<]*', match):
  1556. continue
  1557. else:
  1558. self.report_warning('Youtube gives an alert message: ' + match)
  1559. playlist_title = self._html_search_regex(
  1560. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  1561. page, 'title')
  1562. return self.playlist_result(self._entries(page, playlist_id), playlist_id, playlist_title)
  1563. def _real_extract(self, url):
  1564. # Extract playlist id
  1565. mobj = re.match(self._VALID_URL, url)
  1566. if mobj is None:
  1567. raise ExtractorError('Invalid URL: %s' % url)
  1568. playlist_id = mobj.group(1) or mobj.group(2)
  1569. # Check if it's a video-specific URL
  1570. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1571. if 'v' in query_dict:
  1572. video_id = query_dict['v'][0]
  1573. if self._downloader.params.get('noplaylist'):
  1574. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1575. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1576. else:
  1577. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1578. if playlist_id.startswith('RD') or playlist_id.startswith('UL'):
  1579. # Mixes require a custom extraction process
  1580. return self._extract_mix(playlist_id)
  1581. return self._extract_playlist(playlist_id)
  1582. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  1583. IE_DESC = 'YouTube.com channels'
  1584. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
  1585. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  1586. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  1587. IE_NAME = 'youtube:channel'
  1588. _TESTS = [{
  1589. 'note': 'paginated channel',
  1590. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1591. 'playlist_mincount': 91,
  1592. 'info_dict': {
  1593. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  1594. 'title': 'Uploads from lex will',
  1595. }
  1596. }, {
  1597. 'note': 'Age restricted channel',
  1598. # from https://www.youtube.com/user/DeusExOfficial
  1599. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  1600. 'playlist_mincount': 64,
  1601. 'info_dict': {
  1602. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  1603. 'title': 'Uploads from Deus Ex',
  1604. },
  1605. }]
  1606. def _real_extract(self, url):
  1607. channel_id = self._match_id(url)
  1608. url = self._TEMPLATE_URL % channel_id
  1609. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  1610. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  1611. # otherwise fallback on channel by page extraction
  1612. channel_page = self._download_webpage(
  1613. url + '?view=57', channel_id,
  1614. 'Downloading channel page', fatal=False)
  1615. if channel_page is False:
  1616. channel_playlist_id = False
  1617. else:
  1618. channel_playlist_id = self._html_search_meta(
  1619. 'channelId', channel_page, 'channel id', default=None)
  1620. if not channel_playlist_id:
  1621. channel_playlist_id = self._search_regex(
  1622. r'data-(?:channel-external-|yt)id="([^"]+)"',
  1623. channel_page, 'channel id', default=None)
  1624. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  1625. playlist_id = 'UU' + channel_playlist_id[2:]
  1626. return self.url_result(
  1627. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  1628. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  1629. autogenerated = re.search(r'''(?x)
  1630. class="[^"]*?(?:
  1631. channel-header-autogenerated-label|
  1632. yt-channel-title-autogenerated
  1633. )[^"]*"''', channel_page) is not None
  1634. if autogenerated:
  1635. # The videos are contained in a single page
  1636. # the ajax pages can't be used, they are empty
  1637. entries = [
  1638. self.url_result(
  1639. video_id, 'Youtube', video_id=video_id,
  1640. video_title=video_title)
  1641. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  1642. return self.playlist_result(entries, channel_id)
  1643. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  1644. class YoutubeUserIE(YoutubeChannelIE):
  1645. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1646. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
  1647. _TEMPLATE_URL = 'https://www.youtube.com/user/%s/videos'
  1648. IE_NAME = 'youtube:user'
  1649. _TESTS = [{
  1650. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  1651. 'playlist_mincount': 320,
  1652. 'info_dict': {
  1653. 'title': 'TheLinuxFoundation',
  1654. }
  1655. }, {
  1656. 'url': 'ytuser:phihag',
  1657. 'only_matching': True,
  1658. }]
  1659. @classmethod
  1660. def suitable(cls, url):
  1661. # Don't return True if the url can be extracted with other youtube
  1662. # extractor, the regex would is too permissive and it would match.
  1663. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1664. if any(ie.suitable(url) for ie in other_ies):
  1665. return False
  1666. else:
  1667. return super(YoutubeUserIE, cls).suitable(url)
  1668. class YoutubeUserPlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  1669. IE_DESC = 'YouTube.com user playlists'
  1670. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/user/(?P<id>[^/]+)/playlists'
  1671. IE_NAME = 'youtube:user:playlists'
  1672. _TESTS = [{
  1673. 'url': 'http://www.youtube.com/user/ThirstForScience/playlists',
  1674. 'playlist_mincount': 4,
  1675. 'info_dict': {
  1676. 'id': 'ThirstForScience',
  1677. 'title': 'Thirst for Science',
  1678. },
  1679. }, {
  1680. # with "Load more" button
  1681. 'url': 'http://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  1682. 'playlist_mincount': 70,
  1683. 'info_dict': {
  1684. 'id': 'igorkle1',
  1685. 'title': 'Игорь Клейнер',
  1686. },
  1687. }]
  1688. class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistIE):
  1689. IE_DESC = 'YouTube.com searches'
  1690. # there doesn't appear to be a real limit, for example if you search for
  1691. # 'python' you get more than 8.000.000 results
  1692. _MAX_RESULTS = float('inf')
  1693. IE_NAME = 'youtube:search'
  1694. _SEARCH_KEY = 'ytsearch'
  1695. _EXTRA_QUERY_ARGS = {}
  1696. _TESTS = []
  1697. def _get_n_results(self, query, n):
  1698. """Get a specified number of results for a query"""
  1699. videos = []
  1700. limit = n
  1701. for pagenum in itertools.count(1):
  1702. url_query = {
  1703. 'search_query': query.encode('utf-8'),
  1704. 'page': pagenum,
  1705. 'spf': 'navigate',
  1706. }
  1707. url_query.update(self._EXTRA_QUERY_ARGS)
  1708. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse.urlencode(url_query)
  1709. data = self._download_json(
  1710. result_url, video_id='query "%s"' % query,
  1711. note='Downloading page %s' % pagenum,
  1712. errnote='Unable to download API page')
  1713. html_content = data[1]['body']['content']
  1714. if 'class="search-message' in html_content:
  1715. raise ExtractorError(
  1716. '[youtube] No video results', expected=True)
  1717. new_videos = self._ids_to_results(orderedSet(re.findall(
  1718. r'href="/watch\?v=(.{11})', html_content)))
  1719. videos += new_videos
  1720. if not new_videos or len(videos) > limit:
  1721. break
  1722. if len(videos) > n:
  1723. videos = videos[:n]
  1724. return self.playlist_result(videos, query)
  1725. class YoutubeSearchDateIE(YoutubeSearchIE):
  1726. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1727. _SEARCH_KEY = 'ytsearchdate'
  1728. IE_DESC = 'YouTube.com searches, newest videos first'
  1729. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  1730. class YoutubeSearchURLIE(InfoExtractor):
  1731. IE_DESC = 'YouTube.com search URLs'
  1732. IE_NAME = 'youtube:search_url'
  1733. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1734. _TESTS = [{
  1735. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  1736. 'playlist_mincount': 5,
  1737. 'info_dict': {
  1738. 'title': 'youtube-dl test video',
  1739. }
  1740. }]
  1741. def _real_extract(self, url):
  1742. mobj = re.match(self._VALID_URL, url)
  1743. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  1744. webpage = self._download_webpage(url, query)
  1745. result_code = self._search_regex(
  1746. r'(?s)<ol[^>]+class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1747. part_codes = re.findall(
  1748. r'(?s)<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*>(.*?)</h3>', result_code)
  1749. entries = []
  1750. for part_code in part_codes:
  1751. part_title = self._html_search_regex(
  1752. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1753. part_url_snippet = self._html_search_regex(
  1754. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1755. part_url = compat_urlparse.urljoin(
  1756. 'https://www.youtube.com/', part_url_snippet)
  1757. entries.append({
  1758. '_type': 'url',
  1759. 'url': part_url,
  1760. 'title': part_title,
  1761. })
  1762. return {
  1763. '_type': 'playlist',
  1764. 'entries': entries,
  1765. 'title': query,
  1766. }
  1767. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  1768. IE_DESC = 'YouTube.com (multi-season) shows'
  1769. _VALID_URL = r'https?://www\.youtube\.com/show/(?P<id>[^?#]*)'
  1770. IE_NAME = 'youtube:show'
  1771. _TESTS = [{
  1772. 'url': 'https://www.youtube.com/show/airdisasters',
  1773. 'playlist_mincount': 5,
  1774. 'info_dict': {
  1775. 'id': 'airdisasters',
  1776. 'title': 'Air Disasters',
  1777. }
  1778. }]
  1779. def _real_extract(self, url):
  1780. playlist_id = self._match_id(url)
  1781. return super(YoutubeShowIE, self)._real_extract(
  1782. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  1783. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1784. """
  1785. Base class for feed extractors
  1786. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1787. """
  1788. _LOGIN_REQUIRED = True
  1789. @property
  1790. def IE_NAME(self):
  1791. return 'youtube:%s' % self._FEED_NAME
  1792. def _real_initialize(self):
  1793. self._login()
  1794. def _real_extract(self, url):
  1795. page = self._download_webpage(
  1796. 'https://www.youtube.com/feed/%s' % self._FEED_NAME, self._PLAYLIST_TITLE)
  1797. # The extraction process is the same as for playlists, but the regex
  1798. # for the video ids doesn't contain an index
  1799. ids = []
  1800. more_widget_html = content_html = page
  1801. for page_num in itertools.count(1):
  1802. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1803. # 'recommended' feed has infinite 'load more' and each new portion spins
  1804. # the same videos in (sometimes) slightly different order, so we'll check
  1805. # for unicity and break when portion has no new videos
  1806. new_ids = filter(lambda video_id: video_id not in ids, orderedSet(matches))
  1807. if not new_ids:
  1808. break
  1809. ids.extend(new_ids)
  1810. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1811. if not mobj:
  1812. break
  1813. more = self._download_json(
  1814. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  1815. 'Downloading page #%s' % page_num,
  1816. transform_source=uppercase_escape)
  1817. content_html = more['content_html']
  1818. more_widget_html = more['load_more_widget_html']
  1819. return self.playlist_result(
  1820. self._ids_to_results(ids), playlist_title=self._PLAYLIST_TITLE)
  1821. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  1822. IE_NAME = 'youtube:watchlater'
  1823. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  1824. _VALID_URL = r'https?://www\.youtube\.com/(?:feed/watch_later|playlist\?list=WL)|:ytwatchlater'
  1825. _TESTS = [] # override PlaylistIE tests
  1826. def _real_extract(self, url):
  1827. return self._extract_playlist('WL')
  1828. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1829. IE_NAME = 'youtube:favorites'
  1830. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  1831. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1832. _LOGIN_REQUIRED = True
  1833. def _real_extract(self, url):
  1834. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1835. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  1836. return self.url_result(playlist_id, 'YoutubePlaylist')
  1837. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1838. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  1839. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1840. _FEED_NAME = 'recommended'
  1841. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  1842. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1843. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1844. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1845. _FEED_NAME = 'subscriptions'
  1846. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  1847. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1848. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  1849. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  1850. _FEED_NAME = 'history'
  1851. _PLAYLIST_TITLE = 'Youtube History'
  1852. class YoutubeTruncatedURLIE(InfoExtractor):
  1853. IE_NAME = 'youtube:truncated_url'
  1854. IE_DESC = False # Do not list
  1855. _VALID_URL = r'''(?x)
  1856. (?:https?://)?
  1857. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  1858. (?:watch\?(?:
  1859. feature=[a-z_]+|
  1860. annotation_id=annotation_[^&]+|
  1861. x-yt-cl=[0-9]+|
  1862. hl=[^&]*|
  1863. t=[0-9]+
  1864. )?
  1865. |
  1866. attribution_link\?a=[^&]+
  1867. )
  1868. $
  1869. '''
  1870. _TESTS = [{
  1871. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1872. 'only_matching': True,
  1873. }, {
  1874. 'url': 'http://www.youtube.com/watch?',
  1875. 'only_matching': True,
  1876. }, {
  1877. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  1878. 'only_matching': True,
  1879. }, {
  1880. 'url': 'https://www.youtube.com/watch?feature=foo',
  1881. 'only_matching': True,
  1882. }, {
  1883. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  1884. 'only_matching': True,
  1885. }, {
  1886. 'url': 'https://www.youtube.com/watch?t=2372',
  1887. 'only_matching': True,
  1888. }]
  1889. def _real_extract(self, url):
  1890. raise ExtractorError(
  1891. 'Did you forget to quote the URL? Remember that & is a meta '
  1892. 'character in most shells, so you want to put the URL in quotes, '
  1893. 'like youtube-dl '
  1894. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1895. ' or simply youtube-dl BaW_jenozKc .',
  1896. expected=True)
  1897. class YoutubeTruncatedIDIE(InfoExtractor):
  1898. IE_NAME = 'youtube:truncated_id'
  1899. IE_DESC = False # Do not list
  1900. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  1901. _TESTS = [{
  1902. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  1903. 'only_matching': True,
  1904. }]
  1905. def _real_extract(self, url):
  1906. video_id = self._match_id(url)
  1907. raise ExtractorError(
  1908. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  1909. expected=True)