youtube.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  1. # coding: utf-8
  2. import collections
  3. import itertools
  4. import io
  5. import json
  6. import netrc
  7. import re
  8. import socket
  9. import string
  10. import struct
  11. import traceback
  12. import zlib
  13. from .common import InfoExtractor, SearchInfoExtractor
  14. from .subtitles import SubtitlesInfoExtractor
  15. from ..utils import (
  16. compat_http_client,
  17. compat_parse_qs,
  18. compat_urllib_error,
  19. compat_urllib_parse,
  20. compat_urllib_request,
  21. compat_str,
  22. clean_html,
  23. get_element_by_id,
  24. ExtractorError,
  25. unescapeHTML,
  26. unified_strdate,
  27. orderedSet,
  28. )
  29. class YoutubeBaseInfoExtractor(InfoExtractor):
  30. """Provide base functions for Youtube extractors"""
  31. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  32. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  33. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  34. _NETRC_MACHINE = 'youtube'
  35. # If True it will raise an error if no login info is provided
  36. _LOGIN_REQUIRED = False
  37. def report_lang(self):
  38. """Report attempt to set language."""
  39. self.to_screen(u'Setting language')
  40. def _set_language(self):
  41. request = compat_urllib_request.Request(self._LANG_URL)
  42. try:
  43. self.report_lang()
  44. compat_urllib_request.urlopen(request).read()
  45. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  46. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  47. return False
  48. return True
  49. def _login(self):
  50. (username, password) = self._get_login_info()
  51. # No authentication to be performed
  52. if username is None:
  53. if self._LOGIN_REQUIRED:
  54. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  55. return False
  56. request = compat_urllib_request.Request(self._LOGIN_URL)
  57. try:
  58. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  59. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  60. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  61. return False
  62. galx = None
  63. dsh = None
  64. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  65. if match:
  66. galx = match.group(1)
  67. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  68. if match:
  69. dsh = match.group(1)
  70. # Log in
  71. login_form_strs = {
  72. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  73. u'Email': username,
  74. u'GALX': galx,
  75. u'Passwd': password,
  76. u'PersistentCookie': u'yes',
  77. u'_utf8': u'霱',
  78. u'bgresponse': u'js_disabled',
  79. u'checkConnection': u'',
  80. u'checkedDomains': u'youtube',
  81. u'dnConn': u'',
  82. u'dsh': dsh,
  83. u'pstMsg': u'0',
  84. u'rmShown': u'1',
  85. u'secTok': u'',
  86. u'signIn': u'Sign in',
  87. u'timeStmp': u'',
  88. u'service': u'youtube',
  89. u'uilel': u'3',
  90. u'hl': u'en_US',
  91. }
  92. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  93. # chokes on unicode
  94. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  95. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  96. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  97. try:
  98. self.report_login()
  99. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  100. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  101. self._downloader.report_warning(u'unable to log in: bad username or password')
  102. return False
  103. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  104. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  105. return False
  106. return True
  107. def _confirm_age(self):
  108. age_form = {
  109. 'next_url': '/',
  110. 'action_confirm': 'Confirm',
  111. }
  112. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  113. try:
  114. self.report_age_confirmation()
  115. compat_urllib_request.urlopen(request).read().decode('utf-8')
  116. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  117. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  118. return True
  119. def _real_initialize(self):
  120. if self._downloader is None:
  121. return
  122. if not self._set_language():
  123. return
  124. if not self._login():
  125. return
  126. self._confirm_age()
  127. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  128. IE_DESC = u'YouTube.com'
  129. _VALID_URL = r"""^
  130. (
  131. (?:https?://)? # http(s):// (optional)
  132. (?:(?:(?:(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  133. tube\.majestyc\.net/|
  134. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  135. (?:.*?\#/)? # handle anchor (#/) redirect urls
  136. (?: # the various things that can precede the ID:
  137. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  138. |(?: # or the v= param in all its forms
  139. (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  140. (?:\?|\#!?) # the params delimiter ? or # or #!
  141. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  142. v=
  143. )
  144. ))
  145. |youtu\.be/ # just youtu.be/xxxx
  146. )
  147. )? # all until now is optional -> you can pass the naked ID
  148. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  149. (?(1).+)? # if we found the ID, everything can follow
  150. $"""
  151. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  152. # Listed in order of quality
  153. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '36', '17', '13',
  154. # Apple HTTP Live Streaming
  155. '96', '95', '94', '93', '92', '132', '151',
  156. # 3D
  157. '85', '84', '102', '83', '101', '82', '100',
  158. # Dash video
  159. '138', '137', '248', '136', '247', '135', '246',
  160. '245', '244', '134', '243', '133', '242', '160',
  161. # Dash audio
  162. '141', '172', '140', '171', '139',
  163. ]
  164. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '36', '17', '13',
  165. # Apple HTTP Live Streaming
  166. '96', '95', '94', '93', '92', '132', '151',
  167. # 3D
  168. '85', '102', '84', '101', '83', '100', '82',
  169. # Dash video
  170. '138', '248', '137', '247', '136', '246', '245',
  171. '244', '135', '243', '134', '242', '133', '160',
  172. # Dash audio
  173. '172', '141', '171', '140', '139',
  174. ]
  175. _video_formats_map = {
  176. 'flv': ['35', '34', '6', '5'],
  177. '3gp': ['36', '17', '13'],
  178. 'mp4': ['38', '37', '22', '18'],
  179. 'webm': ['46', '45', '44', '43'],
  180. }
  181. _video_extensions = {
  182. '13': '3gp',
  183. '17': '3gp',
  184. '18': 'mp4',
  185. '22': 'mp4',
  186. '36': '3gp',
  187. '37': 'mp4',
  188. '38': 'mp4',
  189. '43': 'webm',
  190. '44': 'webm',
  191. '45': 'webm',
  192. '46': 'webm',
  193. # 3d videos
  194. '82': 'mp4',
  195. '83': 'mp4',
  196. '84': 'mp4',
  197. '85': 'mp4',
  198. '100': 'webm',
  199. '101': 'webm',
  200. '102': 'webm',
  201. # Apple HTTP Live Streaming
  202. '92': 'mp4',
  203. '93': 'mp4',
  204. '94': 'mp4',
  205. '95': 'mp4',
  206. '96': 'mp4',
  207. '132': 'mp4',
  208. '151': 'mp4',
  209. # Dash mp4
  210. '133': 'mp4',
  211. '134': 'mp4',
  212. '135': 'mp4',
  213. '136': 'mp4',
  214. '137': 'mp4',
  215. '138': 'mp4',
  216. '139': 'mp4',
  217. '140': 'mp4',
  218. '141': 'mp4',
  219. '160': 'mp4',
  220. # Dash webm
  221. '171': 'webm',
  222. '172': 'webm',
  223. '242': 'webm',
  224. '243': 'webm',
  225. '244': 'webm',
  226. '245': 'webm',
  227. '246': 'webm',
  228. '247': 'webm',
  229. '248': 'webm',
  230. }
  231. _video_dimensions = {
  232. '5': '240x400',
  233. '6': '???',
  234. '13': '???',
  235. '17': '144x176',
  236. '18': '360x640',
  237. '22': '720x1280',
  238. '34': '360x640',
  239. '35': '480x854',
  240. '36': '240x320',
  241. '37': '1080x1920',
  242. '38': '3072x4096',
  243. '43': '360x640',
  244. '44': '480x854',
  245. '45': '720x1280',
  246. '46': '1080x1920',
  247. '82': '360p',
  248. '83': '480p',
  249. '84': '720p',
  250. '85': '1080p',
  251. '92': '240p',
  252. '93': '360p',
  253. '94': '480p',
  254. '95': '720p',
  255. '96': '1080p',
  256. '100': '360p',
  257. '101': '480p',
  258. '102': '720p',
  259. '132': '240p',
  260. '151': '72p',
  261. '133': '240p',
  262. '134': '360p',
  263. '135': '480p',
  264. '136': '720p',
  265. '137': '1080p',
  266. '138': '>1080p',
  267. '139': '48k',
  268. '140': '128k',
  269. '141': '256k',
  270. '160': '192p',
  271. '171': '128k',
  272. '172': '256k',
  273. '242': '240p',
  274. '243': '360p',
  275. '244': '480p',
  276. '245': '480p',
  277. '246': '480p',
  278. '247': '720p',
  279. '248': '1080p',
  280. }
  281. _special_itags = {
  282. '82': '3D',
  283. '83': '3D',
  284. '84': '3D',
  285. '85': '3D',
  286. '100': '3D',
  287. '101': '3D',
  288. '102': '3D',
  289. '133': 'DASH Video',
  290. '134': 'DASH Video',
  291. '135': 'DASH Video',
  292. '136': 'DASH Video',
  293. '137': 'DASH Video',
  294. '138': 'DASH Video',
  295. '139': 'DASH Audio',
  296. '140': 'DASH Audio',
  297. '141': 'DASH Audio',
  298. '160': 'DASH Video',
  299. '171': 'DASH Audio',
  300. '172': 'DASH Audio',
  301. '242': 'DASH Video',
  302. '243': 'DASH Video',
  303. '244': 'DASH Video',
  304. '245': 'DASH Video',
  305. '246': 'DASH Video',
  306. '247': 'DASH Video',
  307. '248': 'DASH Video',
  308. }
  309. IE_NAME = u'youtube'
  310. _TESTS = [
  311. {
  312. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  313. u"file": u"BaW_jenozKc.mp4",
  314. u"info_dict": {
  315. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  316. u"uploader": u"Philipp Hagemeister",
  317. u"uploader_id": u"phihag",
  318. u"upload_date": u"20121002",
  319. u"description": u"test chars: \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
  320. }
  321. },
  322. {
  323. u"url": u"http://www.youtube.com/watch?v=1ltcDfZMA3U",
  324. u"file": u"1ltcDfZMA3U.flv",
  325. u"note": u"Test VEVO video (#897)",
  326. u"info_dict": {
  327. u"upload_date": u"20070518",
  328. u"title": u"Maps - It Will Find You",
  329. u"description": u"Music video by Maps performing It Will Find You.",
  330. u"uploader": u"MuteUSA",
  331. u"uploader_id": u"MuteUSA"
  332. }
  333. },
  334. {
  335. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  336. u"file": u"UxxajLWwzqY.mp4",
  337. u"note": u"Test generic use_cipher_signature video (#897)",
  338. u"info_dict": {
  339. u"upload_date": u"20120506",
  340. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  341. u"description": u"md5:3e2666e0a55044490499ea45fe9037b7",
  342. u"uploader": u"Icona Pop",
  343. u"uploader_id": u"IconaPop"
  344. }
  345. },
  346. {
  347. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  348. u"file": u"07FYdnEawAQ.mp4",
  349. u"note": u"Test VEVO video with age protection (#956)",
  350. u"info_dict": {
  351. u"upload_date": u"20130703",
  352. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  353. u"description": u"md5:64249768eec3bc4276236606ea996373",
  354. u"uploader": u"justintimberlakeVEVO",
  355. u"uploader_id": u"justintimberlakeVEVO"
  356. }
  357. },
  358. {
  359. u'url': u'https://www.youtube.com/watch?v=TGi3HqYrWHE',
  360. u'file': u'TGi3HqYrWHE.mp4',
  361. u'note': u'm3u8 video',
  362. u'info_dict': {
  363. u'title': u'Triathlon - Men - London 2012 Olympic Games',
  364. u'description': u'- Men - TR02 - Triathlon - 07 August 2012 - London 2012 Olympic Games',
  365. u'uploader': u'olympic',
  366. u'upload_date': u'20120807',
  367. u'uploader_id': u'olympic',
  368. },
  369. u'params': {
  370. u'skip_download': True,
  371. },
  372. },
  373. ]
  374. @classmethod
  375. def suitable(cls, url):
  376. """Receives a URL and returns True if suitable for this IE."""
  377. if YoutubePlaylistIE.suitable(url): return False
  378. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  379. def __init__(self, *args, **kwargs):
  380. super(YoutubeIE, self).__init__(*args, **kwargs)
  381. self._jsplayer_cache = {}
  382. def report_video_webpage_download(self, video_id):
  383. """Report attempt to download video webpage."""
  384. self.to_screen(u'%s: Downloading video webpage' % video_id)
  385. def report_video_info_webpage_download(self, video_id):
  386. """Report attempt to download video info webpage."""
  387. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  388. def report_information_extraction(self, video_id):
  389. """Report attempt to extract video information."""
  390. self.to_screen(u'%s: Extracting video information' % video_id)
  391. def report_unavailable_format(self, video_id, format):
  392. """Report extracted video URL."""
  393. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  394. def report_rtmp_download(self):
  395. """Indicate the download will use the RTMP protocol."""
  396. self.to_screen(u'RTMP download detected')
  397. def _extract_signature_function(self, video_id, player_url):
  398. id_m = re.match(r'.*-(?P<id>[^.]+)\.(?P<ext>[^.]+)$', player_url)
  399. player_type = id_m.group('ext')
  400. player_id = id_m.group('id')
  401. if player_type == 'js':
  402. code = self._download_webpage(
  403. player_url, video_id,
  404. note=u'Downloading %s player %s' % (player_type, jsplayer_id),
  405. errnote=u'Download of %s failed' % player_url)
  406. return self._parse_sig_js(code)
  407. elif player_tpye == 'swf':
  408. urlh = self._request_webpage(
  409. player_url, video_id,
  410. note=u'Downloading %s player %s' % (player_type, jsplayer_id),
  411. errnote=u'Download of %s failed' % player_url)
  412. code = urlh.read()
  413. return self._parse_sig_swf(code)
  414. else:
  415. assert False, 'Invalid player type %r' % player_type
  416. def _parse_sig_js(self, jscode):
  417. funcname = self._search_regex(
  418. r'signature=([a-zA-Z]+)', jscode,
  419. u'Initial JS player signature function name')
  420. functions = {}
  421. def argidx(varname):
  422. return string.lowercase.index(varname)
  423. def interpret_statement(stmt, local_vars, allow_recursion=20):
  424. if allow_recursion < 0:
  425. raise ExctractorError(u'Recursion limit reached')
  426. if stmt.startswith(u'var '):
  427. stmt = stmt[len(u'var '):]
  428. ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
  429. r'=(?P<expr>.*)$', stmt)
  430. if ass_m:
  431. if ass_m.groupdict().get('index'):
  432. def assign(val):
  433. lvar = local_vars[ass_m.group('out')]
  434. idx = interpret_expression(ass_m.group('index'),
  435. local_vars, allow_recursion)
  436. assert isinstance(idx, int)
  437. lvar[idx] = val
  438. return val
  439. expr = ass_m.group('expr')
  440. else:
  441. def assign(val):
  442. local_vars[ass_m.group('out')] = val
  443. return val
  444. expr = ass_m.group('expr')
  445. elif stmt.startswith(u'return '):
  446. assign = lambda v: v
  447. expr = stmt[len(u'return '):]
  448. else:
  449. raise ExtractorError(
  450. u'Cannot determine left side of statement in %r' % stmt)
  451. v = interpret_expression(expr, local_vars, allow_recursion)
  452. return assign(v)
  453. def interpret_expression(expr, local_vars, allow_recursion):
  454. if expr.isdigit():
  455. return int(expr)
  456. if expr.isalpha():
  457. return local_vars[expr]
  458. m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
  459. if m:
  460. member = m.group('member')
  461. val = local_vars[m.group('in')]
  462. if member == 'split("")':
  463. return list(val)
  464. if member == 'join("")':
  465. return u''.join(val)
  466. if member == 'length':
  467. return len(val)
  468. if member == 'reverse()':
  469. return val[::-1]
  470. slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
  471. if slice_m:
  472. idx = interpret_expression(
  473. slice_m.group('idx'), local_vars, allow_recursion-1)
  474. return val[idx:]
  475. m = re.match(
  476. r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
  477. if m:
  478. val = local_vars[m.group('in')]
  479. idx = interpret_expression(m.group('idx'), local_vars,
  480. allow_recursion-1)
  481. return val[idx]
  482. m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
  483. if m:
  484. a = interpret_expression(m.group('a'),
  485. local_vars, allow_recursion)
  486. b = interpret_expression(m.group('b'),
  487. local_vars, allow_recursion)
  488. return a % b
  489. m = re.match(
  490. r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
  491. if m:
  492. fname = m.group('func')
  493. if fname not in functions:
  494. functions[fname] = extract_function(fname)
  495. argvals = [int(v) if v.isdigit() else local_vars[v]
  496. for v in m.group('args').split(',')]
  497. return functions[fname](argvals)
  498. raise ExtractorError(u'Unsupported JS expression %r' % expr)
  499. def extract_function(funcname):
  500. func_m = re.search(
  501. r'function ' + re.escape(funcname) +
  502. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  503. jscode)
  504. argnames = func_m.group('args').split(',')
  505. def resf(args):
  506. local_vars = dict(zip(argnames, args))
  507. for stmt in func_m.group('code').split(';'):
  508. res = interpret_statement(stmt, local_vars)
  509. return res
  510. return resf
  511. initial_function = extract_function(funcname)
  512. return lambda s: initial_function([s])
  513. def _parse_sig_swf(self, file_contents):
  514. if file_contents[1:3] != b'WS':
  515. raise ExtractorError(
  516. u'Not an SWF file; header is %r' % file_contents[:3])
  517. if file_contents[:1] == b'C':
  518. content = zlib.decompress(file_contents[8:])
  519. else:
  520. raise NotImplementedError(u'Unsupported compression format %r' %
  521. file_contents[:1])
  522. def extract_tags(content):
  523. pos = 0
  524. while pos < len(content):
  525. header16 = struct.unpack('<H', content[pos:pos+2])[0]
  526. pos += 2
  527. tag_code = header16 >> 6
  528. tag_len = header16 & 0x3f
  529. if tag_len == 0x3f:
  530. tag_len = struct.unpack('<I', content[pos:pos+4])[0]
  531. pos += 4
  532. assert pos+tag_len <= len(content)
  533. yield (tag_code, content[pos:pos+tag_len])
  534. pos += tag_len
  535. code_tag = next(tag
  536. for tag_code, tag in extract_tags(content)
  537. if tag_code == 82)
  538. p = code_tag.index(b'\0', 4) + 1
  539. # Parse ABC (AVM2 ByteCode)
  540. def read_int(data=None, pos=None):
  541. if hasattr(data, 'read'):
  542. assert pos is None
  543. res = 0
  544. shift = 0
  545. for _ in range(5):
  546. buf = data.read(1)
  547. assert len(buf) == 1
  548. b = struct.unpack('<B', buf)[0]
  549. res = res | ((b & 0x7f) << shift)
  550. if b & 0x80 == 0:
  551. break
  552. shift += 7
  553. return res
  554. if data is None:
  555. data = code_tag
  556. if pos is None:
  557. pos = p
  558. res = 0
  559. shift = 0
  560. for _ in range(5):
  561. b = struct.unpack('<B', data[pos:pos+1])[0]
  562. pos += 1
  563. res = res | ((b & 0x7f) << shift)
  564. if b & 0x80 == 0:
  565. break
  566. shift += 7
  567. return (res, pos)
  568. assert read_int(b'\x00', 0) == (0, 1)
  569. assert read_int(b'\x10', 0) == (16, 1)
  570. assert read_int(b'\x34', 0) == (0x34, 1)
  571. assert read_int(b'\xb4\x12', 0) == (0x12 * 0x80 + 0x34, 2)
  572. assert read_int(b'\xff\xff\xff\x00', 0) == (0x1fffff, 4)
  573. def u30(*args, **kwargs):
  574. res = read_int(*args, **kwargs)
  575. if isinstance(res, tuple):
  576. assert res[0] & 0xf0000000 == 0
  577. else:
  578. assert res & 0xf0000000 == 0
  579. return res
  580. u32 = read_int
  581. def s32(data=None, pos=None):
  582. v, pos = read_int(data, pos)
  583. if v & 0x80000000 != 0:
  584. v = - ((v ^ 0xffffffff) + 1)
  585. return (v, pos)
  586. assert s32(b'\xff\xff\xff\xff\x0f', 0) == (-1, 5)
  587. def string():
  588. slen, p = u30()
  589. return (code_tag[p:p+slen].decode('utf-8'), p + slen)
  590. def read_byte(data=None, pos=None):
  591. if data is None:
  592. data = code_tag
  593. if pos is None:
  594. pos = p
  595. res = struct.unpack('<B', data[pos:pos+1])[0]
  596. return (res, pos + 1)
  597. # minor_version + major_version
  598. p += 2 + 2
  599. # Constant pool
  600. int_count, p = u30()
  601. for _c in range(1, int_count):
  602. _, p = s32()
  603. uint_count, p = u30()
  604. for _c in range(1, uint_count):
  605. _, p = u32()
  606. double_count, p = u30()
  607. p += (double_count-1) * 8
  608. string_count, p = u30()
  609. constant_strings = [u'']
  610. for _c in range(1, string_count):
  611. s, p = string()
  612. constant_strings.append(s)
  613. namespace_count, p = u30()
  614. for _c in range(1, namespace_count):
  615. p += 1 # kind
  616. _, p = u30() # name
  617. ns_set_count, p = u30()
  618. for _c in range(1, ns_set_count):
  619. count, p = u30()
  620. for _c2 in range(count):
  621. _, p = u30()
  622. multiname_count, p = u30()
  623. MULTINAME_SIZES = {
  624. 0x07: 2, # QName
  625. 0x0d: 2, # QNameA
  626. 0x0f: 1, # RTQName
  627. 0x10: 1, # RTQNameA
  628. 0x11: 0, # RTQNameL
  629. 0x12: 0, # RTQNameLA
  630. 0x09: 2, # Multiname
  631. 0x0e: 2, # MultinameA
  632. 0x1b: 1, # MultinameL
  633. 0x1c: 1, # MultinameLA
  634. }
  635. multinames = [u'']
  636. for _c in range(1, multiname_count):
  637. kind, p = u30()
  638. assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
  639. if kind == 0x07:
  640. namespace_idx, p = u30()
  641. name_idx, p = u30()
  642. multinames.append(constant_strings[name_idx])
  643. else:
  644. multinames.append('[MULTINAME kind: %d]' % kind)
  645. for _c2 in range(MULTINAME_SIZES[kind]):
  646. _, p = u30()
  647. # Methods
  648. method_count, p = u30()
  649. MethodInfo = collections.namedtuple(
  650. 'MethodInfo',
  651. ['NEED_ARGUMENTS', 'NEED_REST'])
  652. method_infos = []
  653. for method_id in range(method_count):
  654. param_count, p = u30()
  655. _, p = u30() # return type
  656. for _ in range(param_count):
  657. _, p = u30() # param type
  658. _, p = u30() # name index (always 0 for youtube)
  659. flags, p = read_byte()
  660. if flags & 0x08 != 0:
  661. # Options present
  662. option_count, p = u30()
  663. for c in range(option_count):
  664. _, p = u30() # val
  665. p += 1 # kind
  666. if flags & 0x80 != 0:
  667. # Param names present
  668. for _ in range(param_count):
  669. _, p = u30() # param name
  670. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  671. method_infos.append(mi)
  672. # Metadata
  673. metadata_count, p = u30()
  674. for _c in range(metadata_count):
  675. _, p = u30() # name
  676. item_count, p = u30()
  677. for _c2 in range(item_count):
  678. _, p = u30() # key
  679. _, p = u30() # value
  680. def parse_traits_info(pos=None):
  681. if pos is None:
  682. pos = p
  683. trait_name_idx, pos = u30(pos=pos)
  684. kind_full, pos = read_byte(pos=pos)
  685. kind = kind_full & 0x0f
  686. attrs = kind_full >> 4
  687. methods = {}
  688. if kind in [0x00, 0x06]: # Slot or Const
  689. _, pos = u30(pos=pos) # Slot id
  690. type_name_idx, pos = u30(pos=pos)
  691. vindex, pos = u30(pos=pos)
  692. if vindex != 0:
  693. _, pos = read_byte(pos=pos) # vkind
  694. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  695. _, pos = u30(pos=pos) # disp_id
  696. method_idx, pos = u30(pos=pos)
  697. methods[multinames[trait_name_idx]] = method_idx
  698. elif kind == 0x04: # Class
  699. _, pos = u30(pos=pos) # slot_id
  700. _, pos = u30(pos=pos) # classi
  701. elif kind == 0x05: # Function
  702. _, pos = u30(pos=pos) # slot_id
  703. function_idx, pos = u30(pos=pos)
  704. methods[function_idx] = multinames[trait_name_idx]
  705. else:
  706. raise ExtractorError(u'Unsupported trait kind %d' % kind)
  707. if attrs & 0x4 != 0: # Metadata present
  708. metadata_count, pos = u30(pos=pos)
  709. for _c3 in range(metadata_count):
  710. _, pos = u30(pos=pos)
  711. return (methods, pos)
  712. # Classes
  713. TARGET_CLASSNAME = u'SignatureDecipher'
  714. searched_idx = multinames.index(TARGET_CLASSNAME)
  715. searched_class_id = None
  716. class_count, p = u30()
  717. for class_id in range(class_count):
  718. name_idx, p = u30()
  719. if name_idx == searched_idx:
  720. # We found the class we're looking for!
  721. searched_class_id = class_id
  722. _, p = u30() # super_name idx
  723. flags, p = read_byte()
  724. if flags & 0x08 != 0: # Protected namespace is present
  725. protected_ns_idx, p = u30()
  726. intrf_count, p = u30()
  727. for _c2 in range(intrf_count):
  728. _, p = u30()
  729. _, p = u30() # iinit
  730. trait_count, p = u30()
  731. for _c2 in range(trait_count):
  732. _, p = parse_traits_info()
  733. if searched_class_id is None:
  734. raise ExtractorError(u'Target class %r not found' %
  735. TARGET_CLASSNAME)
  736. method_names = {}
  737. method_idxs = {}
  738. for class_id in range(class_count):
  739. _, p = u30() # cinit
  740. trait_count, p = u30()
  741. for _c2 in range(trait_count):
  742. trait_methods, p = parse_traits_info()
  743. if class_id == searched_class_id:
  744. method_names.update(trait_methods.items())
  745. method_idxs.update(dict(
  746. (idx, name)
  747. for name, idx in trait_methods.items()))
  748. # Scripts
  749. script_count, p = u30()
  750. for _c in range(script_count):
  751. _, p = u30() # init
  752. trait_count, p = u30()
  753. for _c2 in range(trait_count):
  754. _, p = parse_traits_info()
  755. # Method bodies
  756. method_body_count, p = u30()
  757. Method = collections.namedtuple('Method', ['code', 'local_count'])
  758. methods = {}
  759. for _c in range(method_body_count):
  760. method_idx, p = u30()
  761. max_stack, p = u30()
  762. local_count, p = u30()
  763. init_scope_depth, p = u30()
  764. max_scope_depth, p = u30()
  765. code_length, p = u30()
  766. if method_idx in method_idxs:
  767. m = Method(code_tag[p:p+code_length], local_count)
  768. methods[method_idxs[method_idx]] = m
  769. p += code_length
  770. exception_count, p = u30()
  771. for _c2 in range(exception_count):
  772. _, p = u30() # from
  773. _, p = u30() # to
  774. _, p = u30() # target
  775. _, p = u30() # exc_type
  776. _, p = u30() # var_name
  777. trait_count, p = u30()
  778. for _c2 in range(trait_count):
  779. _, p = parse_traits_info()
  780. assert p == len(code_tag)
  781. assert len(methods) == len(method_idxs)
  782. method_pyfunctions = {}
  783. def extract_function(func_name):
  784. if func_name in method_pyfunctions:
  785. return method_pyfunctions[func_name]
  786. if func_name not in methods:
  787. raise ExtractorError(u'Cannot find function %r' % func_name)
  788. m = methods[func_name]
  789. def resfunc(args):
  790. registers = ['(this)'] + list(args) + [None] * m.local_count
  791. stack = []
  792. coder = io.BytesIO(m.code)
  793. while True:
  794. opcode = struct.unpack('!B', coder.read(1))[0]
  795. if opcode == 36: # pushbyte
  796. v = struct.unpack('!B', coder.read(1))[0]
  797. stack.append(v)
  798. elif opcode == 44: # pushstring
  799. idx = u30(coder)
  800. stack.append(constant_strings[idx])
  801. elif opcode == 48: # pushscope
  802. # We don't implement the scope register, so we'll just
  803. # ignore the popped value
  804. stack.pop()
  805. elif opcode == 70: # callproperty
  806. index = u30(coder)
  807. mname = multinames[index]
  808. arg_count = u30(coder)
  809. args = list(reversed(
  810. [stack.pop() for _ in range(arg_count)]))
  811. obj = stack.pop()
  812. if mname == u'split':
  813. assert len(args) == 1
  814. assert isinstance(args[0], compat_str)
  815. assert isinstance(obj, compat_str)
  816. if args[0] == u'':
  817. res = list(obj)
  818. else:
  819. res = obj.split(args[0])
  820. stack.append(res)
  821. elif mname == u'slice':
  822. assert len(args) == 1
  823. assert isinstance(args[0], int)
  824. assert isinstance(obj, list)
  825. res = obj[args[0]:]
  826. stack.append(res)
  827. elif mname == u'join':
  828. assert len(args) == 1
  829. assert isinstance(args[0], compat_str)
  830. assert isinstance(obj, list)
  831. res = args[0].join(obj)
  832. stack.append(res)
  833. elif mname in method_pyfunctions:
  834. stack.append(method_pyfunctions[mname](args))
  835. else:
  836. raise NotImplementedError(
  837. u'Unsupported property %r on %r'
  838. % (mname, obj))
  839. elif opcode == 72: # returnvalue
  840. res = stack.pop()
  841. return res
  842. elif opcode == 79: # callpropvoid
  843. index = u30(coder)
  844. mname = multinames[index]
  845. arg_count = u30(coder)
  846. args = list(reversed(
  847. [stack.pop() for _ in range(arg_count)]))
  848. obj = stack.pop()
  849. if mname == u'reverse':
  850. assert isinstance(obj, list)
  851. obj.reverse()
  852. else:
  853. raise NotImplementedError(
  854. u'Unsupported (void) property %r on %r'
  855. % (mname, obj))
  856. elif opcode == 93: # findpropstrict
  857. index = u30(coder)
  858. mname = multinames[index]
  859. res = extract_function(mname)
  860. stack.append(res)
  861. elif opcode == 97: # setproperty
  862. index = u30(coder)
  863. value = stack.pop()
  864. idx = stack.pop()
  865. obj = stack.pop()
  866. assert isinstance(obj, list)
  867. assert isinstance(idx, int)
  868. obj[idx] = value
  869. elif opcode == 98: # getlocal
  870. index = u30(coder)
  871. stack.append(registers[index])
  872. elif opcode == 99: # setlocal
  873. index = u30(coder)
  874. value = stack.pop()
  875. registers[index] = value
  876. elif opcode == 102: # getproperty
  877. index = u30(coder)
  878. pname = multinames[index]
  879. if pname == u'length':
  880. obj = stack.pop()
  881. assert isinstance(obj, list)
  882. stack.append(len(obj))
  883. else: # Assume attribute access
  884. idx = stack.pop()
  885. assert isinstance(idx, int)
  886. obj = stack.pop()
  887. assert isinstance(obj, list)
  888. stack.append(obj[idx])
  889. elif opcode == 128: # coerce
  890. _ = u30(coder)
  891. elif opcode == 133: # coerce_s
  892. assert isinstance(stack[-1], (type(None), compat_str))
  893. elif opcode == 164: # modulo
  894. value2 = stack.pop()
  895. value1 = stack.pop()
  896. res = value1 % value2
  897. stack.append(res)
  898. elif opcode == 208: # getlocal_0
  899. stack.append(registers[0])
  900. elif opcode == 209: # getlocal_1
  901. stack.append(registers[1])
  902. elif opcode == 210: # getlocal_2
  903. stack.append(registers[2])
  904. elif opcode == 211: # getlocal_3
  905. stack.append(registers[3])
  906. elif opcode == 214: # setlocal_2
  907. registers[2] = stack.pop()
  908. elif opcode == 215: # setlocal_3
  909. registers[3] = stack.pop()
  910. else:
  911. raise NotImplementedError(
  912. u'Unsupported opcode %d' % opcode)
  913. method_pyfunctions[func_name] = resfunc
  914. return resfunc
  915. initial_function = extract_function(u'decipher')
  916. return lambda s: initial_function([s])
  917. def _decrypt_signature(self, s, video_id, jsplayer_url, age_gate=False):
  918. """Turn the encrypted s field into a working signature"""
  919. if jsplayer_url is not None:
  920. try:
  921. if jsplayer_url not in self._jsplayer_cache:
  922. self._jsplayer_cache[jsplayer_url] = self._extract_signature_function(
  923. video_id, jsplayer_url
  924. )
  925. return self._jsplayer_cache[jsplayer_url]([s])
  926. except Exception as e:
  927. tb = traceback.format_exc()
  928. self._downloader.report_warning(u'Automatic signature extraction failed: ' + tb)
  929. self._downloader.report_warning(u'Warning: Falling back to static signature algorithm')
  930. if age_gate:
  931. # The videos with age protection use another player, so the
  932. # algorithms can be different.
  933. if len(s) == 86:
  934. return s[2:63] + s[82] + s[64:82] + s[63]
  935. if len(s) == 92:
  936. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  937. elif len(s) == 90:
  938. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  939. elif len(s) == 89:
  940. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  941. elif len(s) == 88:
  942. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  943. elif len(s) == 87:
  944. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  945. elif len(s) == 86:
  946. return s[5:34] + s[0] + s[35:38] + s[3] + s[39:45] + s[38] + s[46:53] + s[73] + s[54:73] + s[85] + s[74:85] + s[53]
  947. elif len(s) == 85:
  948. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  949. elif len(s) == 84:
  950. return s[81:36:-1] + s[0] + s[35:2:-1]
  951. elif len(s) == 83:
  952. return s[81:64:-1] + s[82] + s[63:52:-1] + s[45] + s[51:45:-1] + s[1] + s[44:1:-1] + s[0]
  953. elif len(s) == 82:
  954. return s[80:73:-1] + s[81] + s[72:54:-1] + s[2] + s[53:43:-1] + s[0] + s[42:2:-1] + s[43] + s[1] + s[54]
  955. elif len(s) == 81:
  956. return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  957. elif len(s) == 80:
  958. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  959. elif len(s) == 79:
  960. return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  961. else:
  962. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  963. def _decrypt_signature_age_gate(self, s):
  964. # The videos with age protection use another player, so the algorithms
  965. # can be different.
  966. if len(s) == 86:
  967. return s[2:63] + s[82] + s[64:82] + s[63]
  968. else:
  969. # Fallback to the other algortihms
  970. return self._decrypt_signature(s)
  971. def _get_available_subtitles(self, video_id):
  972. try:
  973. sub_list = self._download_webpage(
  974. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  975. video_id, note=False)
  976. except ExtractorError as err:
  977. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  978. return {}
  979. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  980. sub_lang_list = {}
  981. for l in lang_list:
  982. lang = l[1]
  983. params = compat_urllib_parse.urlencode({
  984. 'lang': lang,
  985. 'v': video_id,
  986. 'fmt': self._downloader.params.get('subtitlesformat'),
  987. })
  988. url = u'http://www.youtube.com/api/timedtext?' + params
  989. sub_lang_list[lang] = url
  990. if not sub_lang_list:
  991. self._downloader.report_warning(u'video doesn\'t have subtitles')
  992. return {}
  993. return sub_lang_list
  994. def _get_available_automatic_caption(self, video_id, webpage):
  995. """We need the webpage for getting the captions url, pass it as an
  996. argument to speed up the process."""
  997. sub_format = self._downloader.params.get('subtitlesformat')
  998. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  999. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  1000. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  1001. if mobj is None:
  1002. self._downloader.report_warning(err_msg)
  1003. return {}
  1004. player_config = json.loads(mobj.group(1))
  1005. try:
  1006. args = player_config[u'args']
  1007. caption_url = args[u'ttsurl']
  1008. timestamp = args[u'timestamp']
  1009. # We get the available subtitles
  1010. list_params = compat_urllib_parse.urlencode({
  1011. 'type': 'list',
  1012. 'tlangs': 1,
  1013. 'asrs': 1,
  1014. })
  1015. list_url = caption_url + '&' + list_params
  1016. list_page = self._download_webpage(list_url, video_id)
  1017. caption_list = xml.etree.ElementTree.fromstring(list_page.encode('utf-8'))
  1018. original_lang_node = caption_list.find('track')
  1019. if original_lang_node.attrib.get('kind') != 'asr' :
  1020. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  1021. return {}
  1022. original_lang = original_lang_node.attrib['lang_code']
  1023. sub_lang_list = {}
  1024. for lang_node in caption_list.findall('target'):
  1025. sub_lang = lang_node.attrib['lang_code']
  1026. params = compat_urllib_parse.urlencode({
  1027. 'lang': original_lang,
  1028. 'tlang': sub_lang,
  1029. 'fmt': sub_format,
  1030. 'ts': timestamp,
  1031. 'kind': 'asr',
  1032. })
  1033. sub_lang_list[sub_lang] = caption_url + '&' + params
  1034. return sub_lang_list
  1035. # An extractor error can be raise by the download process if there are
  1036. # no automatic captions but there are subtitles
  1037. except (KeyError, ExtractorError):
  1038. self._downloader.report_warning(err_msg)
  1039. return {}
  1040. def _print_formats(self, formats):
  1041. print('Available formats:')
  1042. for x in formats:
  1043. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  1044. self._video_dimensions.get(x, '???'),
  1045. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  1046. def _extract_id(self, url):
  1047. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1048. if mobj is None:
  1049. raise ExtractorError(u'Invalid URL: %s' % url)
  1050. video_id = mobj.group(2)
  1051. return video_id
  1052. def _get_video_url_list(self, url_map):
  1053. """
  1054. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  1055. with the requested formats.
  1056. """
  1057. req_format = self._downloader.params.get('format', None)
  1058. format_limit = self._downloader.params.get('format_limit', None)
  1059. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  1060. if format_limit is not None and format_limit in available_formats:
  1061. format_list = available_formats[available_formats.index(format_limit):]
  1062. else:
  1063. format_list = available_formats
  1064. existing_formats = [x for x in format_list if x in url_map]
  1065. if len(existing_formats) == 0:
  1066. raise ExtractorError(u'no known formats available for video')
  1067. if self._downloader.params.get('listformats', None):
  1068. self._print_formats(existing_formats)
  1069. return
  1070. if req_format is None or req_format == 'best':
  1071. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1072. elif req_format == 'worst':
  1073. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  1074. elif req_format in ('-1', 'all'):
  1075. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1076. else:
  1077. # Specific formats. We pick the first in a slash-delimeted sequence.
  1078. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  1079. # available in the specified format. For example,
  1080. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1081. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  1082. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  1083. req_formats = req_format.split('/')
  1084. video_url_list = None
  1085. for rf in req_formats:
  1086. if rf in url_map:
  1087. video_url_list = [(rf, url_map[rf])]
  1088. break
  1089. if rf in self._video_formats_map:
  1090. for srf in self._video_formats_map[rf]:
  1091. if srf in url_map:
  1092. video_url_list = [(srf, url_map[srf])]
  1093. break
  1094. else:
  1095. continue
  1096. break
  1097. if video_url_list is None:
  1098. raise ExtractorError(u'requested format not available')
  1099. return video_url_list
  1100. def _extract_from_m3u8(self, manifest_url, video_id):
  1101. url_map = {}
  1102. def _get_urls(_manifest):
  1103. lines = _manifest.split('\n')
  1104. urls = filter(lambda l: l and not l.startswith('#'),
  1105. lines)
  1106. return urls
  1107. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  1108. formats_urls = _get_urls(manifest)
  1109. for format_url in formats_urls:
  1110. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1111. url_map[itag] = format_url
  1112. return url_map
  1113. def _real_extract(self, url):
  1114. if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
  1115. self._downloader.report_warning(u'Did you forget to quote the URL? Remember that & is a meta-character in most shells, so you want to put the URL in quotes, like youtube-dl \'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\' (or simply youtube-dl BaW_jenozKc ).')
  1116. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1117. mobj = re.search(self._NEXT_URL_RE, url)
  1118. if mobj:
  1119. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  1120. video_id = self._extract_id(url)
  1121. # Get video webpage
  1122. self.report_video_webpage_download(video_id)
  1123. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  1124. request = compat_urllib_request.Request(url)
  1125. try:
  1126. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  1127. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1128. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  1129. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  1130. # Attempt to extract SWF player URL
  1131. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1132. if mobj is not None:
  1133. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1134. else:
  1135. player_url = None
  1136. # Get video info
  1137. self.report_video_info_webpage_download(video_id)
  1138. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1139. self.report_age_confirmation()
  1140. age_gate = True
  1141. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1142. # this can be viewed without login into Youtube
  1143. data = compat_urllib_parse.urlencode({'video_id': video_id,
  1144. 'el': 'embedded',
  1145. 'gl': 'US',
  1146. 'hl': 'en',
  1147. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1148. 'asv': 3,
  1149. 'sts':'1588',
  1150. })
  1151. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  1152. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1153. note=False,
  1154. errnote='unable to download video info webpage')
  1155. video_info = compat_parse_qs(video_info_webpage)
  1156. else:
  1157. age_gate = False
  1158. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1159. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1160. % (video_id, el_type))
  1161. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1162. note=False,
  1163. errnote='unable to download video info webpage')
  1164. video_info = compat_parse_qs(video_info_webpage)
  1165. if 'token' in video_info:
  1166. break
  1167. if 'token' not in video_info:
  1168. if 'reason' in video_info:
  1169. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  1170. else:
  1171. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  1172. # Check for "rental" videos
  1173. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1174. raise ExtractorError(u'"rental" videos not supported')
  1175. # Start extracting information
  1176. self.report_information_extraction(video_id)
  1177. # uploader
  1178. if 'author' not in video_info:
  1179. raise ExtractorError(u'Unable to extract uploader name')
  1180. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1181. # uploader_id
  1182. video_uploader_id = None
  1183. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1184. if mobj is not None:
  1185. video_uploader_id = mobj.group(1)
  1186. else:
  1187. self._downloader.report_warning(u'unable to extract uploader nickname')
  1188. # title
  1189. if 'title' not in video_info:
  1190. raise ExtractorError(u'Unable to extract video title')
  1191. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  1192. # thumbnail image
  1193. # We try first to get a high quality image:
  1194. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1195. video_webpage, re.DOTALL)
  1196. if m_thumb is not None:
  1197. video_thumbnail = m_thumb.group(1)
  1198. elif 'thumbnail_url' not in video_info:
  1199. self._downloader.report_warning(u'unable to extract video thumbnail')
  1200. video_thumbnail = ''
  1201. else: # don't panic if we can't find it
  1202. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1203. # upload date
  1204. upload_date = None
  1205. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1206. if mobj is not None:
  1207. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1208. upload_date = unified_strdate(upload_date)
  1209. # description
  1210. video_description = get_element_by_id("eow-description", video_webpage)
  1211. if video_description:
  1212. video_description = clean_html(video_description)
  1213. else:
  1214. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1215. if fd_mobj:
  1216. video_description = unescapeHTML(fd_mobj.group(1))
  1217. else:
  1218. video_description = u''
  1219. # subtitles
  1220. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1221. if self._downloader.params.get('listsubtitles', False):
  1222. self._list_available_subtitles(video_id, video_webpage)
  1223. return
  1224. if 'length_seconds' not in video_info:
  1225. self._downloader.report_warning(u'unable to extract video duration')
  1226. video_duration = ''
  1227. else:
  1228. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  1229. # Decide which formats to download
  1230. try:
  1231. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  1232. if not mobj:
  1233. raise ValueError('Could not find vevo ID')
  1234. info = json.loads(mobj.group(1))
  1235. args = info['args']
  1236. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1237. # this signatures are encrypted
  1238. m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
  1239. if m_s is not None:
  1240. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1241. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1242. m_s = re.search(r'[&,]s=', args.get('adaptive_fmts', u''))
  1243. if m_s is not None:
  1244. if 'url_encoded_fmt_stream_map' in video_info:
  1245. video_info['url_encoded_fmt_stream_map'][0] += ',' + args['adaptive_fmts']
  1246. else:
  1247. video_info['url_encoded_fmt_stream_map'] = [args['adaptive_fmts']]
  1248. elif 'adaptive_fmts' in video_info:
  1249. if 'url_encoded_fmt_stream_map' in video_info:
  1250. video_info['url_encoded_fmt_stream_map'][0] += ',' + video_info['adaptive_fmts'][0]
  1251. else:
  1252. video_info['url_encoded_fmt_stream_map'] = video_info['adaptive_fmts']
  1253. except ValueError:
  1254. pass
  1255. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1256. self.report_rtmp_download()
  1257. video_url_list = [(None, video_info['conn'][0])]
  1258. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  1259. if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
  1260. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1261. url_map = {}
  1262. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  1263. url_data = compat_parse_qs(url_data_str)
  1264. if 'itag' in url_data and 'url' in url_data:
  1265. url = url_data['url'][0]
  1266. if 'sig' in url_data:
  1267. url += '&signature=' + url_data['sig'][0]
  1268. elif 's' in url_data:
  1269. encrypted_sig = url_data['s'][0]
  1270. if self._downloader.params.get('verbose'):
  1271. if age_gate:
  1272. player_version = self._search_regex(r'-(.+)\.swf$',
  1273. player_url if player_url else 'NOT FOUND',
  1274. 'flash player', fatal=False)
  1275. player_desc = 'flash player %s' % player_version
  1276. else:
  1277. player_version = self._search_regex(r'html5player-(.+?)\.js', video_webpage,
  1278. 'html5 player', fatal=False)
  1279. player_desc = u'html5 player %s' % player_version
  1280. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1281. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1282. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1283. if age_gate:
  1284. jsplayer_url = None
  1285. else:
  1286. jsplayer_url_json = self._search_regex(
  1287. r'"assets":.+?"js":\s*("[^"]+")',
  1288. video_webpage, u'JS player URL')
  1289. jsplayer_url = json.loads(jsplayer_url_json)
  1290. signature = self._decrypt_signature(encrypted_sig, video_id, jsplayer_url, age_gate)
  1291. url += '&signature=' + signature
  1292. if 'ratebypass' not in url:
  1293. url += '&ratebypass=yes'
  1294. url_map[url_data['itag'][0]] = url
  1295. video_url_list = self._get_video_url_list(url_map)
  1296. if not video_url_list:
  1297. return
  1298. elif video_info.get('hlsvp'):
  1299. manifest_url = video_info['hlsvp'][0]
  1300. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1301. video_url_list = self._get_video_url_list(url_map)
  1302. if not video_url_list:
  1303. return
  1304. else:
  1305. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  1306. results = []
  1307. for format_param, video_real_url in video_url_list:
  1308. # Extension
  1309. video_extension = self._video_extensions.get(format_param, 'flv')
  1310. video_format = '{0} - {1}{2}'.format(format_param if format_param else video_extension,
  1311. self._video_dimensions.get(format_param, '???'),
  1312. ' ('+self._special_itags[format_param]+')' if format_param in self._special_itags else '')
  1313. results.append({
  1314. 'id': video_id,
  1315. 'url': video_real_url,
  1316. 'uploader': video_uploader,
  1317. 'uploader_id': video_uploader_id,
  1318. 'upload_date': upload_date,
  1319. 'title': video_title,
  1320. 'ext': video_extension,
  1321. 'format': video_format,
  1322. 'thumbnail': video_thumbnail,
  1323. 'description': video_description,
  1324. 'player_url': player_url,
  1325. 'subtitles': video_subtitles,
  1326. 'duration': video_duration
  1327. })
  1328. return results
  1329. class YoutubePlaylistIE(InfoExtractor):
  1330. IE_DESC = u'YouTube.com playlists'
  1331. _VALID_URL = r"""(?:
  1332. (?:https?://)?
  1333. (?:\w+\.)?
  1334. youtube\.com/
  1335. (?:
  1336. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1337. \? (?:.*?&)*? (?:p|a|list)=
  1338. | p/
  1339. )
  1340. ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
  1341. .*
  1342. |
  1343. ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
  1344. )"""
  1345. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  1346. _MAX_RESULTS = 50
  1347. IE_NAME = u'youtube:playlist'
  1348. @classmethod
  1349. def suitable(cls, url):
  1350. """Receives a URL and returns True if suitable for this IE."""
  1351. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1352. def _real_extract(self, url):
  1353. # Extract playlist id
  1354. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1355. if mobj is None:
  1356. raise ExtractorError(u'Invalid URL: %s' % url)
  1357. # Download playlist videos from API
  1358. playlist_id = mobj.group(1) or mobj.group(2)
  1359. videos = []
  1360. for page_num in itertools.count(1):
  1361. start_index = self._MAX_RESULTS * (page_num - 1) + 1
  1362. if start_index >= 1000:
  1363. self._downloader.report_warning(u'Max number of results reached')
  1364. break
  1365. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, start_index)
  1366. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1367. try:
  1368. response = json.loads(page)
  1369. except ValueError as err:
  1370. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1371. if 'feed' not in response:
  1372. raise ExtractorError(u'Got a malformed response from YouTube API')
  1373. playlist_title = response['feed']['title']['$t']
  1374. if 'entry' not in response['feed']:
  1375. # Number of videos is a multiple of self._MAX_RESULTS
  1376. break
  1377. for entry in response['feed']['entry']:
  1378. index = entry['yt$position']['$t']
  1379. if 'media$group' in entry and 'yt$videoid' in entry['media$group']:
  1380. videos.append((
  1381. index,
  1382. 'https://www.youtube.com/watch?v=' + entry['media$group']['yt$videoid']['$t']
  1383. ))
  1384. videos = [v[1] for v in sorted(videos)]
  1385. url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
  1386. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  1387. class YoutubeChannelIE(InfoExtractor):
  1388. IE_DESC = u'YouTube.com channels'
  1389. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1390. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1391. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1392. _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  1393. IE_NAME = u'youtube:channel'
  1394. def extract_videos_from_page(self, page):
  1395. ids_in_page = []
  1396. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1397. if mobj.group(1) not in ids_in_page:
  1398. ids_in_page.append(mobj.group(1))
  1399. return ids_in_page
  1400. def _real_extract(self, url):
  1401. # Extract channel id
  1402. mobj = re.match(self._VALID_URL, url)
  1403. if mobj is None:
  1404. raise ExtractorError(u'Invalid URL: %s' % url)
  1405. # Download channel page
  1406. channel_id = mobj.group(1)
  1407. video_ids = []
  1408. pagenum = 1
  1409. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1410. page = self._download_webpage(url, channel_id,
  1411. u'Downloading page #%s' % pagenum)
  1412. # Extract video identifiers
  1413. ids_in_page = self.extract_videos_from_page(page)
  1414. video_ids.extend(ids_in_page)
  1415. # Download any subsequent channel pages using the json-based channel_ajax query
  1416. if self._MORE_PAGES_INDICATOR in page:
  1417. for pagenum in itertools.count(1):
  1418. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1419. page = self._download_webpage(url, channel_id,
  1420. u'Downloading page #%s' % pagenum)
  1421. page = json.loads(page)
  1422. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1423. video_ids.extend(ids_in_page)
  1424. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1425. break
  1426. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1427. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  1428. url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
  1429. return [self.playlist_result(url_entries, channel_id)]
  1430. class YoutubeUserIE(InfoExtractor):
  1431. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1432. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?)|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1433. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1434. _GDATA_PAGE_SIZE = 50
  1435. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1436. IE_NAME = u'youtube:user'
  1437. @classmethod
  1438. def suitable(cls, url):
  1439. # Don't return True if the url can be extracted with other youtube
  1440. # extractor, the regex would is too permissive and it would match.
  1441. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1442. if any(ie.suitable(url) for ie in other_ies): return False
  1443. else: return super(YoutubeUserIE, cls).suitable(url)
  1444. def _real_extract(self, url):
  1445. # Extract username
  1446. mobj = re.match(self._VALID_URL, url)
  1447. if mobj is None:
  1448. raise ExtractorError(u'Invalid URL: %s' % url)
  1449. username = mobj.group(1)
  1450. # Download video ids using YouTube Data API. Result size per
  1451. # query is limited (currently to 50 videos) so we need to query
  1452. # page by page until there are no video ids - it means we got
  1453. # all of them.
  1454. video_ids = []
  1455. for pagenum in itertools.count(0):
  1456. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1457. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1458. page = self._download_webpage(gdata_url, username,
  1459. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  1460. try:
  1461. response = json.loads(page)
  1462. except ValueError as err:
  1463. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1464. if 'entry' not in response['feed']:
  1465. # Number of videos is a multiple of self._MAX_RESULTS
  1466. break
  1467. # Extract video identifiers
  1468. ids_in_page = []
  1469. for entry in response['feed']['entry']:
  1470. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  1471. video_ids.extend(ids_in_page)
  1472. # A little optimization - if current page is not
  1473. # "full", ie. does not contain PAGE_SIZE video ids then
  1474. # we can assume that this page is the last one - there
  1475. # are no more ids on further pages - no need to query
  1476. # again.
  1477. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1478. break
  1479. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  1480. url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
  1481. return [self.playlist_result(url_results, playlist_title = username)]
  1482. class YoutubeSearchIE(SearchInfoExtractor):
  1483. IE_DESC = u'YouTube.com searches'
  1484. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1485. _MAX_RESULTS = 1000
  1486. IE_NAME = u'youtube:search'
  1487. _SEARCH_KEY = 'ytsearch'
  1488. def report_download_page(self, query, pagenum):
  1489. """Report attempt to download search page with given number."""
  1490. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1491. def _get_n_results(self, query, n):
  1492. """Get a specified number of results for a query"""
  1493. video_ids = []
  1494. pagenum = 0
  1495. limit = n
  1496. while (50 * pagenum) < limit:
  1497. self.report_download_page(query, pagenum+1)
  1498. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1499. request = compat_urllib_request.Request(result_url)
  1500. try:
  1501. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1502. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1503. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  1504. api_response = json.loads(data)['data']
  1505. if not 'items' in api_response:
  1506. raise ExtractorError(u'[youtube] No video results')
  1507. new_ids = list(video['id'] for video in api_response['items'])
  1508. video_ids += new_ids
  1509. limit = min(n, api_response['totalItems'])
  1510. pagenum += 1
  1511. if len(video_ids) > n:
  1512. video_ids = video_ids[:n]
  1513. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  1514. return self.playlist_result(videos, query)
  1515. class YoutubeShowIE(InfoExtractor):
  1516. IE_DESC = u'YouTube.com (multi-season) shows'
  1517. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1518. IE_NAME = u'youtube:show'
  1519. def _real_extract(self, url):
  1520. mobj = re.match(self._VALID_URL, url)
  1521. show_name = mobj.group(1)
  1522. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1523. # There's one playlist for each season of the show
  1524. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1525. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1526. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1527. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1528. """
  1529. Base class for extractors that fetch info from
  1530. http://www.youtube.com/feed_ajax
  1531. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1532. """
  1533. _LOGIN_REQUIRED = True
  1534. _PAGING_STEP = 30
  1535. # use action_load_personal_feed instead of action_load_system_feed
  1536. _PERSONAL_FEED = False
  1537. @property
  1538. def _FEED_TEMPLATE(self):
  1539. action = 'action_load_system_feed'
  1540. if self._PERSONAL_FEED:
  1541. action = 'action_load_personal_feed'
  1542. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1543. @property
  1544. def IE_NAME(self):
  1545. return u'youtube:%s' % self._FEED_NAME
  1546. def _real_initialize(self):
  1547. self._login()
  1548. def _real_extract(self, url):
  1549. feed_entries = []
  1550. # The step argument is available only in 2.7 or higher
  1551. for i in itertools.count(0):
  1552. paging = i*self._PAGING_STEP
  1553. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  1554. u'%s feed' % self._FEED_NAME,
  1555. u'Downloading page %s' % i)
  1556. info = json.loads(info)
  1557. feed_html = info['feed_html']
  1558. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1559. ids = orderedSet(m.group(1) for m in m_ids)
  1560. feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
  1561. if info['paging'] is None:
  1562. break
  1563. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1564. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1565. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1566. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1567. _FEED_NAME = 'subscriptions'
  1568. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1569. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1570. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1571. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1572. _FEED_NAME = 'recommended'
  1573. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1574. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1575. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1576. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1577. _FEED_NAME = 'watch_later'
  1578. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1579. _PAGING_STEP = 100
  1580. _PERSONAL_FEED = True
  1581. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1582. IE_NAME = u'youtube:favorites'
  1583. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1584. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1585. _LOGIN_REQUIRED = True
  1586. def _real_extract(self, url):
  1587. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1588. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1589. return self.url_result(playlist_id, 'YoutubePlaylist')