youtube.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  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_request,
  17. compat_urlparse,
  18. compat_str,
  19. )
  20. from ..utils import (
  21. clean_html,
  22. ExtractorError,
  23. float_or_none,
  24. get_element_by_attribute,
  25. get_element_by_id,
  26. int_or_none,
  27. OnDemandPagedList,
  28. orderedSet,
  29. unescapeHTML,
  30. unified_strdate,
  31. uppercase_escape,
  32. )
  33. class YoutubeBaseInfoExtractor(InfoExtractor):
  34. """Provide base functions for Youtube extractors"""
  35. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  36. _TWOFACTOR_URL = 'https://accounts.google.com/SecondFactor'
  37. _NETRC_MACHINE = 'youtube'
  38. # If True it will raise an error if no login info is provided
  39. _LOGIN_REQUIRED = False
  40. def _set_language(self):
  41. self._set_cookie(
  42. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  43. # YouTube sets the expire time to about two months
  44. expire_time=time.time() + 2 * 30 * 24 * 3600)
  45. def _login(self):
  46. """
  47. Attempt to log in to YouTube.
  48. True is returned if successful or skipped.
  49. False is returned if login failed.
  50. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  51. """
  52. (username, password) = self._get_login_info()
  53. # No authentication to be performed
  54. if username is None:
  55. if self._LOGIN_REQUIRED:
  56. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  57. return True
  58. login_page = self._download_webpage(
  59. self._LOGIN_URL, None,
  60. note='Downloading login page',
  61. errnote='unable to fetch login page', fatal=False)
  62. if login_page is False:
  63. return
  64. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  65. login_page, 'Login GALX parameter')
  66. # Log in
  67. login_form_strs = {
  68. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  69. 'Email': username,
  70. 'GALX': galx,
  71. 'Passwd': password,
  72. 'PersistentCookie': 'yes',
  73. '_utf8': '霱',
  74. 'bgresponse': 'js_disabled',
  75. 'checkConnection': '',
  76. 'checkedDomains': 'youtube',
  77. 'dnConn': '',
  78. 'pstMsg': '0',
  79. 'rmShown': '1',
  80. 'secTok': '',
  81. 'signIn': 'Sign in',
  82. 'timeStmp': '',
  83. 'service': 'youtube',
  84. 'uilel': '3',
  85. 'hl': 'en_US',
  86. }
  87. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  88. # chokes on unicode
  89. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in login_form_strs.items())
  90. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  91. req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  92. login_results = self._download_webpage(
  93. req, None,
  94. note='Logging in', errnote='unable to log in', fatal=False)
  95. if login_results is False:
  96. return False
  97. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  98. raise ExtractorError('Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  99. # Two-Factor
  100. # TODO add SMS and phone call support - these require making a request and then prompting the user
  101. if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', login_results) is not None:
  102. tfa_code = self._get_tfa_info()
  103. if tfa_code is None:
  104. self._downloader.report_warning('Two-factor authentication required. Provide it with --twofactor <code>')
  105. self._downloader.report_warning('(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  106. return False
  107. # Unlike the first login form, secTok and timeStmp are both required for the TFA form
  108. match = re.search(r'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
  109. if match is None:
  110. self._downloader.report_warning('Failed to get secTok - did the page structure change?')
  111. secTok = match.group(1)
  112. match = re.search(r'id="timeStmp"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
  113. if match is None:
  114. self._downloader.report_warning('Failed to get timeStmp - did the page structure change?')
  115. timeStmp = match.group(1)
  116. tfa_form_strs = {
  117. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  118. 'smsToken': '',
  119. 'smsUserPin': tfa_code,
  120. 'smsVerifyPin': 'Verify',
  121. 'PersistentCookie': 'yes',
  122. 'checkConnection': '',
  123. 'checkedDomains': 'youtube',
  124. 'pstMsg': '1',
  125. 'secTok': secTok,
  126. 'timeStmp': timeStmp,
  127. 'service': 'youtube',
  128. 'hl': 'en_US',
  129. }
  130. tfa_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k, v in tfa_form_strs.items())
  131. tfa_data = compat_urllib_parse.urlencode(tfa_form).encode('ascii')
  132. tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
  133. tfa_results = self._download_webpage(
  134. tfa_req, None,
  135. note='Submitting TFA code', errnote='unable to submit tfa', fatal=False)
  136. if tfa_results is False:
  137. return False
  138. if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', tfa_results) is not None:
  139. self._downloader.report_warning('Two-factor code expired. Please try again, or use a one-use backup code instead.')
  140. return False
  141. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  142. self._downloader.report_warning('unable to log in - did the page structure change?')
  143. return False
  144. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  145. self._downloader.report_warning('Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  146. return False
  147. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  148. self._downloader.report_warning('unable to log in: bad username or password')
  149. return False
  150. return True
  151. def _real_initialize(self):
  152. if self._downloader is None:
  153. return
  154. self._set_language()
  155. if not self._login():
  156. return
  157. class YoutubeIE(YoutubeBaseInfoExtractor):
  158. IE_DESC = 'YouTube.com'
  159. _VALID_URL = r"""(?x)^
  160. (
  161. (?:https?://|//) # http(s):// or protocol-independent URL
  162. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  163. (?:www\.)?deturl\.com/www\.youtube\.com/|
  164. (?:www\.)?pwnyoutube\.com/|
  165. (?:www\.)?yourepeat\.com/|
  166. tube\.majestyc\.net/|
  167. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  168. (?:.*?\#/)? # handle anchor (#/) redirect urls
  169. (?: # the various things that can precede the ID:
  170. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  171. |(?: # or the v= param in all its forms
  172. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  173. (?:\?|\#!?) # the params delimiter ? or # or #!
  174. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  175. v=
  176. )
  177. ))
  178. |youtu\.be/ # just youtu.be/xxxx
  179. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  180. )
  181. )? # all until now is optional -> you can pass the naked ID
  182. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  183. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  184. (?(1).+)? # if we found the ID, everything can follow
  185. $"""
  186. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  187. _formats = {
  188. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  189. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  190. '13': {'ext': '3gp'},
  191. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  192. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  193. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  194. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  195. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  196. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  197. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  198. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  199. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  200. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  201. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  202. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  203. # 3d videos
  204. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
  205. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
  206. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
  207. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
  208. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
  209. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
  210. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
  211. # Apple HTTP Live Streaming
  212. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  213. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
  214. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
  215. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
  216. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
  217. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  218. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
  219. # DASH mp4 video
  220. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  221. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  222. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  223. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  224. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  225. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, # Height can vary (https://github.com/rg3/youtube-dl/issues/4559)
  226. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  227. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  228. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'h264'},
  229. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'h264'},
  230. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'vcodec': 'h264'},
  231. # Dash mp4 audio
  232. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 48, 'preference': -50, 'container': 'm4a_dash'},
  233. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 128, 'preference': -50, 'container': 'm4a_dash'},
  234. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 256, 'preference': -50, 'container': 'm4a_dash'},
  235. # Dash webm
  236. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  237. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  238. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  239. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  240. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  241. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  242. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'container': 'webm', 'vcodec': 'VP9'},
  243. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  244. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  245. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  246. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  247. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  248. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  249. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  250. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  251. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  252. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'VP9'},
  253. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'VP9'},
  254. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'VP9'},
  255. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'vcodec': 'VP9'},
  256. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'VP9'},
  257. # Dash webm audio
  258. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  259. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  260. # Dash webm audio with opus inside
  261. '249': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50, 'preference': -50},
  262. '250': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70, 'preference': -50},
  263. '251': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160, 'preference': -50},
  264. # RTMP (unnamed)
  265. '_rtmp': {'protocol': 'rtmp'},
  266. }
  267. IE_NAME = 'youtube'
  268. _TESTS = [
  269. {
  270. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKc',
  271. 'info_dict': {
  272. 'id': 'BaW_jenozKc',
  273. 'ext': 'mp4',
  274. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  275. 'uploader': 'Philipp Hagemeister',
  276. 'uploader_id': 'phihag',
  277. 'upload_date': '20121002',
  278. '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 .',
  279. 'categories': ['Science & Technology'],
  280. 'like_count': int,
  281. 'dislike_count': int,
  282. }
  283. },
  284. {
  285. 'url': 'http://www.youtube.com/watch?v=UxxajLWwzqY',
  286. 'note': 'Test generic use_cipher_signature video (#897)',
  287. 'info_dict': {
  288. 'id': 'UxxajLWwzqY',
  289. 'ext': 'mp4',
  290. 'upload_date': '20120506',
  291. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  292. 'description': 'md5:fea86fda2d5a5784273df5c7cc994d9f',
  293. 'uploader': 'Icona Pop',
  294. 'uploader_id': 'IconaPop',
  295. }
  296. },
  297. {
  298. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  299. 'note': 'Test VEVO video with age protection (#956)',
  300. 'info_dict': {
  301. 'id': '07FYdnEawAQ',
  302. 'ext': 'mp4',
  303. 'upload_date': '20130703',
  304. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  305. 'description': 'md5:64249768eec3bc4276236606ea996373',
  306. 'uploader': 'justintimberlakeVEVO',
  307. 'uploader_id': 'justintimberlakeVEVO',
  308. }
  309. },
  310. {
  311. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  312. 'note': 'Embed-only video (#1746)',
  313. 'info_dict': {
  314. 'id': 'yZIXLfi8CZQ',
  315. 'ext': 'mp4',
  316. 'upload_date': '20120608',
  317. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  318. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  319. 'uploader': 'SET India',
  320. 'uploader_id': 'setindia'
  321. }
  322. },
  323. {
  324. 'url': 'http://www.youtube.com/watch?v=a9LDPn-MO4I',
  325. 'note': '256k DASH audio (format 141) via DASH manifest',
  326. 'info_dict': {
  327. 'id': 'a9LDPn-MO4I',
  328. 'ext': 'm4a',
  329. 'upload_date': '20121002',
  330. 'uploader_id': '8KVIDEO',
  331. 'description': '',
  332. 'uploader': '8KVIDEO',
  333. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  334. },
  335. 'params': {
  336. 'youtube_include_dash_manifest': True,
  337. 'format': '141',
  338. },
  339. },
  340. # DASH manifest with encrypted signature
  341. {
  342. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  343. 'info_dict': {
  344. 'id': 'IB3lcPjvWLA',
  345. 'ext': 'm4a',
  346. 'title': 'Afrojack, Spree Wilson - The Spark ft. Spree Wilson',
  347. 'description': 'md5:12e7067fa6735a77bdcbb58cb1187d2d',
  348. 'uploader': 'AfrojackVEVO',
  349. 'uploader_id': 'AfrojackVEVO',
  350. 'upload_date': '20131011',
  351. },
  352. 'params': {
  353. 'youtube_include_dash_manifest': True,
  354. 'format': '141',
  355. },
  356. },
  357. # JS player signature function name containing $
  358. {
  359. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  360. 'info_dict': {
  361. 'id': 'nfWlot6h_JM',
  362. 'ext': 'm4a',
  363. 'title': 'Taylor Swift - Shake It Off',
  364. 'description': 'md5:2acfda1b285bdd478ccec22f9918199d',
  365. 'uploader': 'TaylorSwiftVEVO',
  366. 'uploader_id': 'TaylorSwiftVEVO',
  367. 'upload_date': '20140818',
  368. },
  369. 'params': {
  370. 'youtube_include_dash_manifest': True,
  371. 'format': '141',
  372. },
  373. },
  374. # Controversy video
  375. {
  376. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  377. 'info_dict': {
  378. 'id': 'T4XJQO3qol8',
  379. 'ext': 'mp4',
  380. 'upload_date': '20100909',
  381. 'uploader': 'The Amazing Atheist',
  382. 'uploader_id': 'TheAmazingAtheist',
  383. 'title': 'Burning Everyone\'s Koran',
  384. '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',
  385. }
  386. },
  387. # Normal age-gate video (No vevo, embed allowed)
  388. {
  389. 'url': 'http://youtube.com/watch?v=HtVdAasjOgU',
  390. 'info_dict': {
  391. 'id': 'HtVdAasjOgU',
  392. 'ext': 'mp4',
  393. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  394. 'description': 're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  395. 'uploader': 'The Witcher',
  396. 'uploader_id': 'WitcherGame',
  397. 'upload_date': '20140605',
  398. },
  399. },
  400. # Age-gate video with encrypted signature
  401. {
  402. 'url': 'http://www.youtube.com/watch?v=6kLq3WMV1nU',
  403. 'info_dict': {
  404. 'id': '6kLq3WMV1nU',
  405. 'ext': 'mp4',
  406. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  407. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  408. 'uploader': 'LloydVEVO',
  409. 'uploader_id': 'LloydVEVO',
  410. 'upload_date': '20110629',
  411. },
  412. },
  413. # video_info is None (https://github.com/rg3/youtube-dl/issues/4421)
  414. {
  415. 'url': '__2ABJjxzNo',
  416. 'info_dict': {
  417. 'id': '__2ABJjxzNo',
  418. 'ext': 'mp4',
  419. 'upload_date': '20100430',
  420. 'uploader_id': 'deadmau5',
  421. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  422. 'uploader': 'deadmau5',
  423. 'title': 'Deadmau5 - Some Chords (HD)',
  424. },
  425. 'expected_warnings': [
  426. 'DASH manifest missing',
  427. ]
  428. },
  429. # Olympics (https://github.com/rg3/youtube-dl/issues/4431)
  430. {
  431. 'url': 'lqQg6PlCWgI',
  432. 'info_dict': {
  433. 'id': 'lqQg6PlCWgI',
  434. 'ext': 'mp4',
  435. 'upload_date': '20120731',
  436. 'uploader_id': 'olympic',
  437. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  438. 'uploader': 'Olympics',
  439. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  440. },
  441. 'params': {
  442. 'skip_download': 'requires avconv',
  443. }
  444. },
  445. # Non-square pixels
  446. {
  447. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  448. 'info_dict': {
  449. 'id': '_b-2C3KPAM0',
  450. 'ext': 'mp4',
  451. 'stretched_ratio': 16 / 9.,
  452. 'upload_date': '20110310',
  453. 'uploader_id': 'AllenMeow',
  454. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  455. 'uploader': '孫艾倫',
  456. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  457. },
  458. },
  459. # url_encoded_fmt_stream_map is empty string
  460. {
  461. 'url': 'qEJwOuvDf7I',
  462. 'info_dict': {
  463. 'id': 'qEJwOuvDf7I',
  464. 'ext': 'mp4',
  465. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  466. 'description': '',
  467. 'upload_date': '20150404',
  468. 'uploader_id': 'spbelect',
  469. 'uploader': 'Наблюдатели Петербурга',
  470. },
  471. 'params': {
  472. 'skip_download': 'requires avconv',
  473. }
  474. },
  475. ]
  476. def __init__(self, *args, **kwargs):
  477. super(YoutubeIE, self).__init__(*args, **kwargs)
  478. self._player_cache = {}
  479. def report_video_info_webpage_download(self, video_id):
  480. """Report attempt to download video info webpage."""
  481. self.to_screen('%s: Downloading video info webpage' % video_id)
  482. def report_information_extraction(self, video_id):
  483. """Report attempt to extract video information."""
  484. self.to_screen('%s: Extracting video information' % video_id)
  485. def report_unavailable_format(self, video_id, format):
  486. """Report extracted video URL."""
  487. self.to_screen('%s: Format %s not available' % (video_id, format))
  488. def report_rtmp_download(self):
  489. """Indicate the download will use the RTMP protocol."""
  490. self.to_screen('RTMP download detected')
  491. def _signature_cache_id(self, example_sig):
  492. """ Return a string representation of a signature """
  493. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  494. def _extract_signature_function(self, video_id, player_url, example_sig):
  495. id_m = re.match(
  496. r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
  497. player_url)
  498. if not id_m:
  499. raise ExtractorError('Cannot identify player %r' % player_url)
  500. player_type = id_m.group('ext')
  501. player_id = id_m.group('id')
  502. # Read from filesystem cache
  503. func_id = '%s_%s_%s' % (
  504. player_type, player_id, self._signature_cache_id(example_sig))
  505. assert os.path.basename(func_id) == func_id
  506. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  507. if cache_spec is not None:
  508. return lambda s: ''.join(s[i] for i in cache_spec)
  509. download_note = (
  510. 'Downloading player %s' % player_url
  511. if self._downloader.params.get('verbose') else
  512. 'Downloading %s player %s' % (player_type, player_id)
  513. )
  514. if player_type == 'js':
  515. code = self._download_webpage(
  516. player_url, video_id,
  517. note=download_note,
  518. errnote='Download of %s failed' % player_url)
  519. res = self._parse_sig_js(code)
  520. elif player_type == 'swf':
  521. urlh = self._request_webpage(
  522. player_url, video_id,
  523. note=download_note,
  524. errnote='Download of %s failed' % player_url)
  525. code = urlh.read()
  526. res = self._parse_sig_swf(code)
  527. else:
  528. assert False, 'Invalid player type %r' % player_type
  529. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  530. cache_res = res(test_string)
  531. cache_spec = [ord(c) for c in cache_res]
  532. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  533. return res
  534. def _print_sig_code(self, func, example_sig):
  535. def gen_sig_code(idxs):
  536. def _genslice(start, end, step):
  537. starts = '' if start == 0 else str(start)
  538. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  539. steps = '' if step == 1 else (':%d' % step)
  540. return 's[%s%s%s]' % (starts, ends, steps)
  541. step = None
  542. # Quelch pyflakes warnings - start will be set when step is set
  543. start = '(Never used)'
  544. for i, prev in zip(idxs[1:], idxs[:-1]):
  545. if step is not None:
  546. if i - prev == step:
  547. continue
  548. yield _genslice(start, prev, step)
  549. step = None
  550. continue
  551. if i - prev in [-1, 1]:
  552. step = i - prev
  553. start = prev
  554. continue
  555. else:
  556. yield 's[%d]' % prev
  557. if step is None:
  558. yield 's[%d]' % i
  559. else:
  560. yield _genslice(start, i, step)
  561. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  562. cache_res = func(test_string)
  563. cache_spec = [ord(c) for c in cache_res]
  564. expr_code = ' + '.join(gen_sig_code(cache_spec))
  565. signature_id_tuple = '(%s)' % (
  566. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  567. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  568. ' return %s\n') % (signature_id_tuple, expr_code)
  569. self.to_screen('Extracted signature function:\n' + code)
  570. def _parse_sig_js(self, jscode):
  571. funcname = self._search_regex(
  572. r'\.sig\|\|([a-zA-Z0-9$]+)\(', jscode,
  573. 'Initial JS player signature function name')
  574. jsi = JSInterpreter(jscode)
  575. initial_function = jsi.extract_function(funcname)
  576. return lambda s: initial_function([s])
  577. def _parse_sig_swf(self, file_contents):
  578. swfi = SWFInterpreter(file_contents)
  579. TARGET_CLASSNAME = 'SignatureDecipher'
  580. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  581. initial_function = swfi.extract_function(searched_class, 'decipher')
  582. return lambda s: initial_function([s])
  583. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  584. """Turn the encrypted s field into a working signature"""
  585. if player_url is None:
  586. raise ExtractorError('Cannot decrypt signature without player_url')
  587. if player_url.startswith('//'):
  588. player_url = 'https:' + player_url
  589. try:
  590. player_id = (player_url, self._signature_cache_id(s))
  591. if player_id not in self._player_cache:
  592. func = self._extract_signature_function(
  593. video_id, player_url, s
  594. )
  595. self._player_cache[player_id] = func
  596. func = self._player_cache[player_id]
  597. if self._downloader.params.get('youtube_print_sig_code'):
  598. self._print_sig_code(func, s)
  599. return func(s)
  600. except Exception as e:
  601. tb = traceback.format_exc()
  602. raise ExtractorError(
  603. 'Signature extraction failed: ' + tb, cause=e)
  604. def _get_subtitles(self, video_id, webpage):
  605. try:
  606. subs_doc = self._download_xml(
  607. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  608. video_id, note=False)
  609. except ExtractorError as err:
  610. self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
  611. return {}
  612. sub_lang_list = {}
  613. for track in subs_doc.findall('track'):
  614. lang = track.attrib['lang_code']
  615. if lang in sub_lang_list:
  616. continue
  617. sub_formats = []
  618. for ext in ['sbv', 'vtt', 'srt']:
  619. params = compat_urllib_parse.urlencode({
  620. 'lang': lang,
  621. 'v': video_id,
  622. 'fmt': ext,
  623. 'name': track.attrib['name'].encode('utf-8'),
  624. })
  625. sub_formats.append({
  626. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  627. 'ext': ext,
  628. })
  629. sub_lang_list[lang] = sub_formats
  630. if not sub_lang_list:
  631. self._downloader.report_warning('video doesn\'t have subtitles')
  632. return {}
  633. return sub_lang_list
  634. def _get_automatic_captions(self, video_id, webpage):
  635. """We need the webpage for getting the captions url, pass it as an
  636. argument to speed up the process."""
  637. self.to_screen('%s: Looking for automatic captions' % video_id)
  638. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  639. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  640. if mobj is None:
  641. self._downloader.report_warning(err_msg)
  642. return {}
  643. player_config = json.loads(mobj.group(1))
  644. try:
  645. args = player_config['args']
  646. caption_url = args['ttsurl']
  647. timestamp = args['timestamp']
  648. # We get the available subtitles
  649. list_params = compat_urllib_parse.urlencode({
  650. 'type': 'list',
  651. 'tlangs': 1,
  652. 'asrs': 1,
  653. })
  654. list_url = caption_url + '&' + list_params
  655. caption_list = self._download_xml(list_url, video_id)
  656. original_lang_node = caption_list.find('track')
  657. if original_lang_node is None:
  658. self._downloader.report_warning('Video doesn\'t have automatic captions')
  659. return {}
  660. original_lang = original_lang_node.attrib['lang_code']
  661. caption_kind = original_lang_node.attrib.get('kind', '')
  662. sub_lang_list = {}
  663. for lang_node in caption_list.findall('target'):
  664. sub_lang = lang_node.attrib['lang_code']
  665. sub_formats = []
  666. for ext in ['sbv', 'vtt', 'srt']:
  667. params = compat_urllib_parse.urlencode({
  668. 'lang': original_lang,
  669. 'tlang': sub_lang,
  670. 'fmt': ext,
  671. 'ts': timestamp,
  672. 'kind': caption_kind,
  673. })
  674. sub_formats.append({
  675. 'url': caption_url + '&' + params,
  676. 'ext': ext,
  677. })
  678. sub_lang_list[sub_lang] = sub_formats
  679. return sub_lang_list
  680. # An extractor error can be raise by the download process if there are
  681. # no automatic captions but there are subtitles
  682. except (KeyError, ExtractorError):
  683. self._downloader.report_warning(err_msg)
  684. return {}
  685. @classmethod
  686. def extract_id(cls, url):
  687. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  688. if mobj is None:
  689. raise ExtractorError('Invalid URL: %s' % url)
  690. video_id = mobj.group(2)
  691. return video_id
  692. def _extract_from_m3u8(self, manifest_url, video_id):
  693. url_map = {}
  694. def _get_urls(_manifest):
  695. lines = _manifest.split('\n')
  696. urls = filter(lambda l: l and not l.startswith('#'),
  697. lines)
  698. return urls
  699. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  700. formats_urls = _get_urls(manifest)
  701. for format_url in formats_urls:
  702. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  703. url_map[itag] = format_url
  704. return url_map
  705. def _extract_annotations(self, video_id):
  706. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  707. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  708. def _parse_dash_manifest(
  709. self, video_id, dash_manifest_url, player_url, age_gate):
  710. def decrypt_sig(mobj):
  711. s = mobj.group(1)
  712. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  713. return '/signature/%s' % dec_s
  714. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  715. dash_doc = self._download_xml(
  716. dash_manifest_url, video_id,
  717. note='Downloading DASH manifest',
  718. errnote='Could not download DASH manifest')
  719. formats = []
  720. for r in dash_doc.findall('.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  721. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  722. if url_el is None:
  723. continue
  724. format_id = r.attrib['id']
  725. video_url = url_el.text
  726. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  727. f = {
  728. 'format_id': format_id,
  729. 'url': video_url,
  730. 'width': int_or_none(r.attrib.get('width')),
  731. 'height': int_or_none(r.attrib.get('height')),
  732. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  733. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  734. 'filesize': filesize,
  735. 'fps': int_or_none(r.attrib.get('frameRate')),
  736. }
  737. try:
  738. existing_format = next(
  739. fo for fo in formats
  740. if fo['format_id'] == format_id)
  741. except StopIteration:
  742. full_info = self._formats.get(format_id, {}).copy()
  743. full_info.update(f)
  744. formats.append(full_info)
  745. else:
  746. existing_format.update(f)
  747. return formats
  748. def _real_extract(self, url):
  749. proto = (
  750. 'http' if self._downloader.params.get('prefer_insecure', False)
  751. else 'https')
  752. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  753. mobj = re.search(self._NEXT_URL_RE, url)
  754. if mobj:
  755. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  756. video_id = self.extract_id(url)
  757. # Get video webpage
  758. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  759. video_webpage = self._download_webpage(url, video_id)
  760. # Attempt to extract SWF player URL
  761. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  762. if mobj is not None:
  763. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  764. else:
  765. player_url = None
  766. # Get video info
  767. embed_webpage = None
  768. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  769. age_gate = True
  770. # We simulate the access to the video from www.youtube.com/v/{video_id}
  771. # this can be viewed without login into Youtube
  772. url = proto + '://www.youtube.com/embed/%s' % video_id
  773. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  774. data = compat_urllib_parse.urlencode({
  775. 'video_id': video_id,
  776. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  777. 'sts': self._search_regex(
  778. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  779. })
  780. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  781. video_info_webpage = self._download_webpage(
  782. video_info_url, video_id,
  783. note='Refetching age-gated info webpage',
  784. errnote='unable to download video info webpage')
  785. video_info = compat_parse_qs(video_info_webpage)
  786. else:
  787. age_gate = False
  788. try:
  789. # Try looking directly into the video webpage
  790. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  791. if not mobj:
  792. raise ValueError('Could not find ytplayer.config') # caught below
  793. json_code = uppercase_escape(mobj.group(1))
  794. ytplayer_config = json.loads(json_code)
  795. args = ytplayer_config['args']
  796. # Convert to the same format returned by compat_parse_qs
  797. video_info = dict((k, [v]) for k, v in args.items())
  798. if ('url_encoded_fmt_stream_map' not in args or
  799. args['url_encoded_fmt_stream_map'] == ''):
  800. raise ValueError('No stream_map present') # caught below
  801. except ValueError:
  802. # We fallback to the get_video_info pages (used by the embed page)
  803. self.report_video_info_webpage_download(video_id)
  804. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  805. video_info_url = (
  806. '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  807. % (proto, video_id, el_type))
  808. video_info_webpage = self._download_webpage(
  809. video_info_url,
  810. video_id, note=False,
  811. errnote='unable to download video info webpage')
  812. video_info = compat_parse_qs(video_info_webpage)
  813. if 'token' in video_info:
  814. break
  815. if 'token' not in video_info:
  816. if 'reason' in video_info:
  817. raise ExtractorError(
  818. 'YouTube said: %s' % video_info['reason'][0],
  819. expected=True, video_id=video_id)
  820. else:
  821. raise ExtractorError(
  822. '"token" parameter not in video info for unknown reason',
  823. video_id=video_id)
  824. if 'view_count' in video_info:
  825. view_count = int(video_info['view_count'][0])
  826. else:
  827. view_count = None
  828. # Check for "rental" videos
  829. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  830. raise ExtractorError('"rental" videos not supported')
  831. # Start extracting information
  832. self.report_information_extraction(video_id)
  833. # uploader
  834. if 'author' not in video_info:
  835. raise ExtractorError('Unable to extract uploader name')
  836. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  837. # uploader_id
  838. video_uploader_id = None
  839. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  840. if mobj is not None:
  841. video_uploader_id = mobj.group(1)
  842. else:
  843. self._downloader.report_warning('unable to extract uploader nickname')
  844. # title
  845. if 'title' in video_info:
  846. video_title = video_info['title'][0]
  847. else:
  848. self._downloader.report_warning('Unable to extract video title')
  849. video_title = '_'
  850. # thumbnail image
  851. # We try first to get a high quality image:
  852. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  853. video_webpage, re.DOTALL)
  854. if m_thumb is not None:
  855. video_thumbnail = m_thumb.group(1)
  856. elif 'thumbnail_url' not in video_info:
  857. self._downloader.report_warning('unable to extract video thumbnail')
  858. video_thumbnail = None
  859. else: # don't panic if we can't find it
  860. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  861. # upload date
  862. upload_date = None
  863. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  864. if mobj is None:
  865. mobj = re.search(
  866. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  867. video_webpage)
  868. if mobj is not None:
  869. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  870. upload_date = unified_strdate(upload_date)
  871. m_cat_container = self._search_regex(
  872. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  873. video_webpage, 'categories', default=None)
  874. if m_cat_container:
  875. category = self._html_search_regex(
  876. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  877. default=None)
  878. video_categories = None if category is None else [category]
  879. else:
  880. video_categories = None
  881. # description
  882. video_description = get_element_by_id("eow-description", video_webpage)
  883. if video_description:
  884. video_description = re.sub(r'''(?x)
  885. <a\s+
  886. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  887. title="([^"]+)"\s+
  888. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  889. class="yt-uix-redirect-link"\s*>
  890. [^<]+
  891. </a>
  892. ''', r'\1', video_description)
  893. video_description = clean_html(video_description)
  894. else:
  895. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  896. if fd_mobj:
  897. video_description = unescapeHTML(fd_mobj.group(1))
  898. else:
  899. video_description = ''
  900. def _extract_count(count_name):
  901. count = self._search_regex(
  902. r'id="watch-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name),
  903. video_webpage, count_name, default=None)
  904. if count is not None:
  905. return int(count.replace(',', ''))
  906. return None
  907. like_count = _extract_count('like')
  908. dislike_count = _extract_count('dislike')
  909. # subtitles
  910. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  911. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  912. if 'length_seconds' not in video_info:
  913. self._downloader.report_warning('unable to extract video duration')
  914. video_duration = None
  915. else:
  916. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  917. # annotations
  918. video_annotations = None
  919. if self._downloader.params.get('writeannotations', False):
  920. video_annotations = self._extract_annotations(video_id)
  921. def _map_to_format_list(urlmap):
  922. formats = []
  923. for itag, video_real_url in urlmap.items():
  924. dct = {
  925. 'format_id': itag,
  926. 'url': video_real_url,
  927. 'player_url': player_url,
  928. }
  929. if itag in self._formats:
  930. dct.update(self._formats[itag])
  931. formats.append(dct)
  932. return formats
  933. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  934. self.report_rtmp_download()
  935. formats = [{
  936. 'format_id': '_rtmp',
  937. 'protocol': 'rtmp',
  938. 'url': video_info['conn'][0],
  939. 'player_url': player_url,
  940. }]
  941. elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
  942. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  943. if 'rtmpe%3Dyes' in encoded_url_map:
  944. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  945. url_map = {}
  946. for url_data_str in encoded_url_map.split(','):
  947. url_data = compat_parse_qs(url_data_str)
  948. if 'itag' not in url_data or 'url' not in url_data:
  949. continue
  950. format_id = url_data['itag'][0]
  951. url = url_data['url'][0]
  952. if 'sig' in url_data:
  953. url += '&signature=' + url_data['sig'][0]
  954. elif 's' in url_data:
  955. encrypted_sig = url_data['s'][0]
  956. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  957. jsplayer_url_json = self._search_regex(
  958. ASSETS_RE,
  959. embed_webpage if age_gate else video_webpage,
  960. 'JS player URL (1)', default=None)
  961. if not jsplayer_url_json and not age_gate:
  962. # We need the embed website after all
  963. if embed_webpage is None:
  964. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  965. embed_webpage = self._download_webpage(
  966. embed_url, video_id, 'Downloading embed webpage')
  967. jsplayer_url_json = self._search_regex(
  968. ASSETS_RE, embed_webpage, 'JS player URL')
  969. player_url = json.loads(jsplayer_url_json)
  970. if player_url is None:
  971. player_url_json = self._search_regex(
  972. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  973. video_webpage, 'age gate player URL')
  974. player_url = json.loads(player_url_json)
  975. if self._downloader.params.get('verbose'):
  976. if player_url is None:
  977. player_version = 'unknown'
  978. player_desc = 'unknown'
  979. else:
  980. if player_url.endswith('swf'):
  981. player_version = self._search_regex(
  982. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  983. 'flash player', fatal=False)
  984. player_desc = 'flash player %s' % player_version
  985. else:
  986. player_version = self._search_regex(
  987. r'html5player-([^/]+?)(?:/html5player)?\.js',
  988. player_url,
  989. 'html5 player', fatal=False)
  990. player_desc = 'html5 player %s' % player_version
  991. parts_sizes = self._signature_cache_id(encrypted_sig)
  992. self.to_screen('{%s} signature length %s, %s' %
  993. (format_id, parts_sizes, player_desc))
  994. signature = self._decrypt_signature(
  995. encrypted_sig, video_id, player_url, age_gate)
  996. url += '&signature=' + signature
  997. if 'ratebypass' not in url:
  998. url += '&ratebypass=yes'
  999. url_map[format_id] = url
  1000. formats = _map_to_format_list(url_map)
  1001. elif video_info.get('hlsvp'):
  1002. manifest_url = video_info['hlsvp'][0]
  1003. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1004. formats = _map_to_format_list(url_map)
  1005. else:
  1006. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1007. # Look for the DASH manifest
  1008. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1009. dash_mpd = video_info.get('dashmpd')
  1010. if dash_mpd:
  1011. dash_manifest_url = dash_mpd[0]
  1012. try:
  1013. dash_formats = self._parse_dash_manifest(
  1014. video_id, dash_manifest_url, player_url, age_gate)
  1015. except (ExtractorError, KeyError) as e:
  1016. self.report_warning(
  1017. 'Skipping DASH manifest: %r' % e, video_id)
  1018. else:
  1019. # Hide the formats we found through non-DASH
  1020. dash_keys = set(df['format_id'] for df in dash_formats)
  1021. for f in formats:
  1022. if f['format_id'] in dash_keys:
  1023. f['format_id'] = 'nondash-%s' % f['format_id']
  1024. f['preference'] = f.get('preference', 0) - 10000
  1025. formats.extend(dash_formats)
  1026. # Check for malformed aspect ratio
  1027. stretched_m = re.search(
  1028. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  1029. video_webpage)
  1030. if stretched_m:
  1031. ratio = float(stretched_m.group('w')) / float(stretched_m.group('h'))
  1032. for f in formats:
  1033. if f.get('vcodec') != 'none':
  1034. f['stretched_ratio'] = ratio
  1035. self._sort_formats(formats)
  1036. return {
  1037. 'id': video_id,
  1038. 'uploader': video_uploader,
  1039. 'uploader_id': video_uploader_id,
  1040. 'upload_date': upload_date,
  1041. 'title': video_title,
  1042. 'thumbnail': video_thumbnail,
  1043. 'description': video_description,
  1044. 'categories': video_categories,
  1045. 'subtitles': video_subtitles,
  1046. 'automatic_captions': automatic_captions,
  1047. 'duration': video_duration,
  1048. 'age_limit': 18 if age_gate else 0,
  1049. 'annotations': video_annotations,
  1050. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1051. 'view_count': view_count,
  1052. 'like_count': like_count,
  1053. 'dislike_count': dislike_count,
  1054. 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
  1055. 'formats': formats,
  1056. }
  1057. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1058. IE_DESC = 'YouTube.com playlists'
  1059. _VALID_URL = r"""(?x)(?:
  1060. (?:https?://)?
  1061. (?:\w+\.)?
  1062. youtube\.com/
  1063. (?:
  1064. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  1065. \? (?:.*?&)*? (?:p|a|list)=
  1066. | p/
  1067. )
  1068. (
  1069. (?:PL|LL|EC|UU|FL|RD|UL)?[0-9A-Za-z-_]{10,}
  1070. # Top tracks, they can also include dots
  1071. |(?:MC)[\w\.]*
  1072. )
  1073. .*
  1074. |
  1075. ((?:PL|LL|EC|UU|FL|RD|UL)[0-9A-Za-z-_]{10,})
  1076. )"""
  1077. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1078. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1079. IE_NAME = 'youtube:playlist'
  1080. _TESTS = [{
  1081. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1082. 'info_dict': {
  1083. 'title': 'ytdl test PL',
  1084. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1085. },
  1086. 'playlist_count': 3,
  1087. }, {
  1088. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1089. 'info_dict': {
  1090. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1091. 'title': 'YDL_Empty_List',
  1092. },
  1093. 'playlist_count': 0,
  1094. }, {
  1095. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  1096. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1097. 'info_dict': {
  1098. 'title': '29C3: Not my department',
  1099. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1100. },
  1101. 'playlist_count': 95,
  1102. }, {
  1103. 'note': 'issue #673',
  1104. 'url': 'PLBB231211A4F62143',
  1105. 'info_dict': {
  1106. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  1107. 'id': 'PLBB231211A4F62143',
  1108. },
  1109. 'playlist_mincount': 26,
  1110. }, {
  1111. 'note': 'Large playlist',
  1112. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  1113. 'info_dict': {
  1114. 'title': 'Uploads from Cauchemar',
  1115. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  1116. },
  1117. 'playlist_mincount': 799,
  1118. }, {
  1119. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1120. 'info_dict': {
  1121. 'title': 'YDL_safe_search',
  1122. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1123. },
  1124. 'playlist_count': 2,
  1125. }, {
  1126. 'note': 'embedded',
  1127. 'url': 'http://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1128. 'playlist_count': 4,
  1129. 'info_dict': {
  1130. 'title': 'JODA15',
  1131. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1132. }
  1133. }, {
  1134. 'note': 'Embedded SWF player',
  1135. 'url': 'http://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  1136. 'playlist_count': 4,
  1137. 'info_dict': {
  1138. 'title': 'JODA7',
  1139. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  1140. }
  1141. }, {
  1142. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  1143. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  1144. 'info_dict': {
  1145. 'title': 'Uploads from Interstellar Movie',
  1146. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  1147. },
  1148. 'playlist_mincout': 21,
  1149. }]
  1150. def _real_initialize(self):
  1151. self._login()
  1152. def _ids_to_results(self, ids):
  1153. return [
  1154. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1155. for vid_id in ids]
  1156. def _extract_mix(self, playlist_id):
  1157. # The mixes are generated from a single video
  1158. # the id of the playlist is just 'RD' + video_id
  1159. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1160. webpage = self._download_webpage(
  1161. url, playlist_id, 'Downloading Youtube mix')
  1162. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1163. title_span = (
  1164. search_title('playlist-title') or
  1165. search_title('title long-title') or
  1166. search_title('title'))
  1167. title = clean_html(title_span)
  1168. ids = orderedSet(re.findall(
  1169. r'''(?xs)data-video-username=".*?".*?
  1170. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  1171. webpage))
  1172. url_results = self._ids_to_results(ids)
  1173. return self.playlist_result(url_results, playlist_id, title)
  1174. def _extract_playlist(self, playlist_id):
  1175. url = self._TEMPLATE_URL % playlist_id
  1176. page = self._download_webpage(url, playlist_id)
  1177. more_widget_html = content_html = page
  1178. # Check if the playlist exists or is private
  1179. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  1180. raise ExtractorError(
  1181. 'The playlist doesn\'t exist or is private, use --username or '
  1182. '--netrc to access it.',
  1183. expected=True)
  1184. # Extract the video ids from the playlist pages
  1185. ids = []
  1186. for page_num in itertools.count(1):
  1187. matches = re.finditer(self._VIDEO_RE, content_html)
  1188. # We remove the duplicates and the link with index 0
  1189. # (it's not the first video of the playlist)
  1190. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1191. ids.extend(new_ids)
  1192. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1193. if not mobj:
  1194. break
  1195. more = self._download_json(
  1196. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  1197. 'Downloading page #%s' % page_num,
  1198. transform_source=uppercase_escape)
  1199. content_html = more['content_html']
  1200. if not content_html.strip():
  1201. # Some webpages show a "Load more" button but they don't
  1202. # have more videos
  1203. break
  1204. more_widget_html = more['load_more_widget_html']
  1205. playlist_title = self._html_search_regex(
  1206. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  1207. page, 'title')
  1208. url_results = self._ids_to_results(ids)
  1209. return self.playlist_result(url_results, playlist_id, playlist_title)
  1210. def _real_extract(self, url):
  1211. # Extract playlist id
  1212. mobj = re.match(self._VALID_URL, url)
  1213. if mobj is None:
  1214. raise ExtractorError('Invalid URL: %s' % url)
  1215. playlist_id = mobj.group(1) or mobj.group(2)
  1216. # Check if it's a video-specific URL
  1217. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1218. if 'v' in query_dict:
  1219. video_id = query_dict['v'][0]
  1220. if self._downloader.params.get('noplaylist'):
  1221. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1222. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1223. else:
  1224. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1225. if playlist_id.startswith('RD') or playlist_id.startswith('UL'):
  1226. # Mixes require a custom extraction process
  1227. return self._extract_mix(playlist_id)
  1228. return self._extract_playlist(playlist_id)
  1229. class YoutubeChannelIE(InfoExtractor):
  1230. IE_DESC = 'YouTube.com channels'
  1231. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
  1232. IE_NAME = 'youtube:channel'
  1233. _TESTS = [{
  1234. 'note': 'paginated channel',
  1235. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1236. 'playlist_mincount': 91,
  1237. 'info_dict': {
  1238. 'id': 'UCKfVa3S1e4PHvxWcwyMMg8w',
  1239. }
  1240. }]
  1241. def extract_videos_from_page(self, page):
  1242. ids_in_page = []
  1243. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1244. if mobj.group(1) not in ids_in_page:
  1245. ids_in_page.append(mobj.group(1))
  1246. return ids_in_page
  1247. def _real_extract(self, url):
  1248. channel_id = self._match_id(url)
  1249. video_ids = []
  1250. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1251. channel_page = self._download_webpage(url, channel_id)
  1252. autogenerated = re.search(r'''(?x)
  1253. class="[^"]*?(?:
  1254. channel-header-autogenerated-label|
  1255. yt-channel-title-autogenerated
  1256. )[^"]*"''', channel_page) is not None
  1257. if autogenerated:
  1258. # The videos are contained in a single page
  1259. # the ajax pages can't be used, they are empty
  1260. video_ids = self.extract_videos_from_page(channel_page)
  1261. entries = [
  1262. self.url_result(video_id, 'Youtube', video_id=video_id)
  1263. for video_id in video_ids]
  1264. return self.playlist_result(entries, channel_id)
  1265. def _entries():
  1266. more_widget_html = content_html = channel_page
  1267. for pagenum in itertools.count(1):
  1268. ids_in_page = self.extract_videos_from_page(content_html)
  1269. for video_id in ids_in_page:
  1270. yield self.url_result(
  1271. video_id, 'Youtube', video_id=video_id)
  1272. mobj = re.search(
  1273. r'data-uix-load-more-href="/?(?P<more>[^"]+)"',
  1274. more_widget_html)
  1275. if not mobj:
  1276. break
  1277. more = self._download_json(
  1278. 'https://youtube.com/%s' % mobj.group('more'), channel_id,
  1279. 'Downloading page #%s' % (pagenum + 1),
  1280. transform_source=uppercase_escape)
  1281. content_html = more['content_html']
  1282. more_widget_html = more['load_more_widget_html']
  1283. return self.playlist_result(_entries(), channel_id)
  1284. class YoutubeUserIE(InfoExtractor):
  1285. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1286. _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_-]+)'
  1287. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1288. _GDATA_PAGE_SIZE = 50
  1289. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1290. IE_NAME = 'youtube:user'
  1291. _TESTS = [{
  1292. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  1293. 'playlist_mincount': 320,
  1294. 'info_dict': {
  1295. 'title': 'TheLinuxFoundation',
  1296. }
  1297. }, {
  1298. 'url': 'ytuser:phihag',
  1299. 'only_matching': True,
  1300. }]
  1301. @classmethod
  1302. def suitable(cls, url):
  1303. # Don't return True if the url can be extracted with other youtube
  1304. # extractor, the regex would is too permissive and it would match.
  1305. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1306. if any(ie.suitable(url) for ie in other_ies):
  1307. return False
  1308. else:
  1309. return super(YoutubeUserIE, cls).suitable(url)
  1310. def _real_extract(self, url):
  1311. username = self._match_id(url)
  1312. # Download video ids using YouTube Data API. Result size per
  1313. # query is limited (currently to 50 videos) so we need to query
  1314. # page by page until there are no video ids - it means we got
  1315. # all of them.
  1316. def download_page(pagenum):
  1317. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1318. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1319. page = self._download_webpage(
  1320. gdata_url, username,
  1321. 'Downloading video ids from %d to %d' % (
  1322. start_index, start_index + self._GDATA_PAGE_SIZE))
  1323. try:
  1324. response = json.loads(page)
  1325. except ValueError as err:
  1326. raise ExtractorError('Invalid JSON in API response: ' + compat_str(err))
  1327. if 'entry' not in response['feed']:
  1328. return
  1329. # Extract video identifiers
  1330. entries = response['feed']['entry']
  1331. for entry in entries:
  1332. title = entry['title']['$t']
  1333. video_id = entry['id']['$t'].split('/')[-1]
  1334. yield {
  1335. '_type': 'url',
  1336. 'url': video_id,
  1337. 'ie_key': 'Youtube',
  1338. 'id': video_id,
  1339. 'title': title,
  1340. }
  1341. url_results = OnDemandPagedList(download_page, self._GDATA_PAGE_SIZE)
  1342. return self.playlist_result(url_results, playlist_title=username)
  1343. class YoutubeSearchIE(SearchInfoExtractor):
  1344. IE_DESC = 'YouTube.com searches'
  1345. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1346. _MAX_RESULTS = 1000
  1347. IE_NAME = 'youtube:search'
  1348. _SEARCH_KEY = 'ytsearch'
  1349. def _get_n_results(self, query, n):
  1350. """Get a specified number of results for a query"""
  1351. video_ids = []
  1352. pagenum = 0
  1353. limit = n
  1354. PAGE_SIZE = 50
  1355. while (PAGE_SIZE * pagenum) < limit:
  1356. result_url = self._API_URL % (
  1357. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1358. (PAGE_SIZE * pagenum) + 1)
  1359. data_json = self._download_webpage(
  1360. result_url, video_id='query "%s"' % query,
  1361. note='Downloading page %s' % (pagenum + 1),
  1362. errnote='Unable to download API page')
  1363. data = json.loads(data_json)
  1364. api_response = data['data']
  1365. if 'items' not in api_response:
  1366. raise ExtractorError(
  1367. '[youtube] No video results', expected=True)
  1368. new_ids = list(video['id'] for video in api_response['items'])
  1369. video_ids += new_ids
  1370. limit = min(n, api_response['totalItems'])
  1371. pagenum += 1
  1372. if len(video_ids) > n:
  1373. video_ids = video_ids[:n]
  1374. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1375. for video_id in video_ids]
  1376. return self.playlist_result(videos, query)
  1377. class YoutubeSearchDateIE(YoutubeSearchIE):
  1378. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1379. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1380. _SEARCH_KEY = 'ytsearchdate'
  1381. IE_DESC = 'YouTube.com searches, newest videos first'
  1382. class YoutubeSearchURLIE(InfoExtractor):
  1383. IE_DESC = 'YouTube.com search URLs'
  1384. IE_NAME = 'youtube:search_url'
  1385. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1386. _TESTS = [{
  1387. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  1388. 'playlist_mincount': 5,
  1389. 'info_dict': {
  1390. 'title': 'youtube-dl test video',
  1391. }
  1392. }]
  1393. def _real_extract(self, url):
  1394. mobj = re.match(self._VALID_URL, url)
  1395. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1396. webpage = self._download_webpage(url, query)
  1397. result_code = self._search_regex(
  1398. r'(?s)<ol[^>]+class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1399. part_codes = re.findall(
  1400. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1401. entries = []
  1402. for part_code in part_codes:
  1403. part_title = self._html_search_regex(
  1404. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1405. part_url_snippet = self._html_search_regex(
  1406. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1407. part_url = compat_urlparse.urljoin(
  1408. 'https://www.youtube.com/', part_url_snippet)
  1409. entries.append({
  1410. '_type': 'url',
  1411. 'url': part_url,
  1412. 'title': part_title,
  1413. })
  1414. return {
  1415. '_type': 'playlist',
  1416. 'entries': entries,
  1417. 'title': query,
  1418. }
  1419. class YoutubeShowIE(InfoExtractor):
  1420. IE_DESC = 'YouTube.com (multi-season) shows'
  1421. _VALID_URL = r'https?://www\.youtube\.com/show/(?P<id>[^?#]*)'
  1422. IE_NAME = 'youtube:show'
  1423. _TESTS = [{
  1424. 'url': 'http://www.youtube.com/show/airdisasters',
  1425. 'playlist_mincount': 3,
  1426. 'info_dict': {
  1427. 'id': 'airdisasters',
  1428. 'title': 'Air Disasters',
  1429. }
  1430. }]
  1431. def _real_extract(self, url):
  1432. mobj = re.match(self._VALID_URL, url)
  1433. playlist_id = mobj.group('id')
  1434. webpage = self._download_webpage(
  1435. url, playlist_id, 'Downloading show webpage')
  1436. # There's one playlist for each season of the show
  1437. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1438. self.to_screen('%s: Found %s seasons' % (playlist_id, len(m_seasons)))
  1439. entries = [
  1440. self.url_result(
  1441. 'https://www.youtube.com' + season.group(1), 'YoutubePlaylist')
  1442. for season in m_seasons
  1443. ]
  1444. title = self._og_search_title(webpage, fatal=False)
  1445. return {
  1446. '_type': 'playlist',
  1447. 'id': playlist_id,
  1448. 'title': title,
  1449. 'entries': entries,
  1450. }
  1451. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1452. """
  1453. Base class for extractors that fetch info from
  1454. http://www.youtube.com/feed_ajax
  1455. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1456. """
  1457. _LOGIN_REQUIRED = True
  1458. # use action_load_personal_feed instead of action_load_system_feed
  1459. _PERSONAL_FEED = False
  1460. @property
  1461. def _FEED_TEMPLATE(self):
  1462. action = 'action_load_system_feed'
  1463. if self._PERSONAL_FEED:
  1464. action = 'action_load_personal_feed'
  1465. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1466. @property
  1467. def IE_NAME(self):
  1468. return 'youtube:%s' % self._FEED_NAME
  1469. def _real_initialize(self):
  1470. self._login()
  1471. def _real_extract(self, url):
  1472. feed_entries = []
  1473. paging = 0
  1474. for i in itertools.count(1):
  1475. info = self._download_json(
  1476. self._FEED_TEMPLATE % paging,
  1477. '%s feed' % self._FEED_NAME,
  1478. 'Downloading page %s' % i,
  1479. transform_source=uppercase_escape)
  1480. feed_html = info.get('feed_html') or info.get('content_html')
  1481. load_more_widget_html = info.get('load_more_widget_html') or feed_html
  1482. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1483. ids = orderedSet(m.group(1) for m in m_ids)
  1484. feed_entries.extend(
  1485. self.url_result(video_id, 'Youtube', video_id=video_id)
  1486. for video_id in ids)
  1487. mobj = re.search(
  1488. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1489. load_more_widget_html)
  1490. if mobj is None:
  1491. break
  1492. paging = mobj.group('paging')
  1493. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1494. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1495. IE_NAME = 'youtube:recommended'
  1496. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  1497. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1498. _FEED_NAME = 'recommended'
  1499. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  1500. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  1501. IE_NAME = 'youtube:watchlater'
  1502. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  1503. _VALID_URL = r'https?://www\.youtube\.com/(?:feed/watch_later|playlist\?list=WL)|:ytwatchlater'
  1504. _TESTS = [] # override PlaylistIE tests
  1505. def _real_extract(self, url):
  1506. return self._extract_playlist('WL')
  1507. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1508. IE_NAME = 'youtube:history'
  1509. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  1510. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  1511. _FEED_NAME = 'history'
  1512. _PERSONAL_FEED = True
  1513. _PLAYLIST_TITLE = 'Youtube Watch History'
  1514. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1515. IE_NAME = 'youtube:favorites'
  1516. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  1517. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1518. _LOGIN_REQUIRED = True
  1519. def _real_extract(self, url):
  1520. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1521. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  1522. return self.url_result(playlist_id, 'YoutubePlaylist')
  1523. class YoutubeSubscriptionsIE(YoutubePlaylistIE):
  1524. IE_NAME = 'youtube:subscriptions'
  1525. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1526. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1527. _TESTS = []
  1528. def _real_extract(self, url):
  1529. title = 'Youtube Subscriptions'
  1530. page = self._download_webpage('https://www.youtube.com/feed/subscriptions', title)
  1531. # The extraction process is the same as for playlists, but the regex
  1532. # for the video ids doesn't contain an index
  1533. ids = []
  1534. more_widget_html = content_html = page
  1535. for page_num in itertools.count(1):
  1536. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1537. new_ids = orderedSet(matches)
  1538. ids.extend(new_ids)
  1539. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1540. if not mobj:
  1541. break
  1542. more = self._download_json(
  1543. 'https://youtube.com/%s' % mobj.group('more'), title,
  1544. 'Downloading page #%s' % page_num,
  1545. transform_source=uppercase_escape)
  1546. content_html = more['content_html']
  1547. more_widget_html = more['load_more_widget_html']
  1548. return {
  1549. '_type': 'playlist',
  1550. 'title': title,
  1551. 'entries': self._ids_to_results(ids),
  1552. }
  1553. class YoutubeTruncatedURLIE(InfoExtractor):
  1554. IE_NAME = 'youtube:truncated_url'
  1555. IE_DESC = False # Do not list
  1556. _VALID_URL = r'''(?x)
  1557. (?:https?://)?
  1558. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  1559. (?:watch\?(?:
  1560. feature=[a-z_]+|
  1561. annotation_id=annotation_[^&]+|
  1562. x-yt-cl=[0-9]+|
  1563. hl=[^&]*|
  1564. )?
  1565. |
  1566. attribution_link\?a=[^&]+
  1567. )
  1568. $
  1569. '''
  1570. _TESTS = [{
  1571. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1572. 'only_matching': True,
  1573. }, {
  1574. 'url': 'http://www.youtube.com/watch?',
  1575. 'only_matching': True,
  1576. }, {
  1577. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  1578. 'only_matching': True,
  1579. }, {
  1580. 'url': 'https://www.youtube.com/watch?feature=foo',
  1581. 'only_matching': True,
  1582. }, {
  1583. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  1584. 'only_matching': True,
  1585. }]
  1586. def _real_extract(self, url):
  1587. raise ExtractorError(
  1588. 'Did you forget to quote the URL? Remember that & is a meta '
  1589. 'character in most shells, so you want to put the URL in quotes, '
  1590. 'like youtube-dl '
  1591. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1592. ' or simply youtube-dl BaW_jenozKc .',
  1593. expected=True)
  1594. class YoutubeTruncatedIDIE(InfoExtractor):
  1595. IE_NAME = 'youtube:truncated_id'
  1596. IE_DESC = False # Do not list
  1597. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  1598. _TESTS = [{
  1599. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  1600. 'only_matching': True,
  1601. }]
  1602. def _real_extract(self, url):
  1603. video_id = self._match_id(url)
  1604. raise ExtractorError(
  1605. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  1606. expected=True)