youtube.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  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. print('Entering function %s(%r)' % (func_name, args))
  791. registers = ['(this)'] + list(args) + [None] * m.local_count
  792. stack = []
  793. coder = io.BytesIO(m.code)
  794. while True:
  795. opcode = struct.unpack('!B', coder.read(1))[0]
  796. if opcode == 208: # getlocal_0
  797. stack.append(registers[0])
  798. elif opcode == 209: # getlocal_1
  799. stack.append(registers[1])
  800. elif opcode == 210: # getlocal_2
  801. stack.append(registers[2])
  802. elif opcode == 36: # pushbyte
  803. v = struct.unpack('!B', coder.read(1))[0]
  804. stack.append(v)
  805. elif opcode == 44: # pushstring
  806. idx = u30(coder)
  807. stack.append(constant_strings[idx])
  808. elif opcode == 48: # pushscope
  809. # We don't implement the scope register, so we'll just
  810. # ignore the popped value
  811. stack.pop()
  812. elif opcode == 70: # callproperty
  813. index = u30(coder)
  814. mname = multinames[index]
  815. arg_count = u30(coder)
  816. args = list(reversed(
  817. [stack.pop() for _ in range(arg_count)]))
  818. obj = stack.pop()
  819. if mname == u'split':
  820. assert len(args) == 1
  821. assert isinstance(args[0], compat_str)
  822. assert isinstance(obj, compat_str)
  823. if args[0] == u'':
  824. res = list(obj)
  825. else:
  826. res = obj.split(args[0])
  827. stack.append(res)
  828. elif mname in method_pyfunctions:
  829. stack.append(method_pyfunctions[mname](args))
  830. else:
  831. raise NotImplementedError(
  832. u'Unsupported property %r on %r'
  833. % (mname, obj))
  834. elif opcode == 93: # findpropstrict
  835. index = u30(coder)
  836. mname = multinames[index]
  837. res = extract_function(mname)
  838. stack.append(res)
  839. elif opcode == 97: # setproperty
  840. index = u30(coder)
  841. value = stack.pop()
  842. idx = stack.pop()
  843. obj = stack.pop()
  844. assert isinstance(obj, list)
  845. assert isinstance(idx, int)
  846. obj[idx] = value
  847. elif opcode == 98: # getlocal
  848. index = u30(coder)
  849. stack.append(registers[index])
  850. elif opcode == 99: # setlocal
  851. index = u30(coder)
  852. value = stack.pop()
  853. registers[index] = value
  854. elif opcode == 102: # getproperty
  855. index = u30(coder)
  856. pname = multinames[index]
  857. if pname == u'length':
  858. obj = stack.pop()
  859. assert isinstance(obj, list)
  860. stack.append(len(obj))
  861. else: # Assume attribute access
  862. idx = stack.pop()
  863. assert isinstance(idx, int)
  864. obj = stack.pop()
  865. assert isinstance(obj, list)
  866. stack.append(obj[idx])
  867. elif opcode == 128: # coerce
  868. _ = u30(coder)
  869. elif opcode == 133: # coerce_s
  870. assert isinstance(stack[-1], (type(None), compat_str))
  871. elif opcode == 164: # modulo
  872. value2 = stack.pop()
  873. value1 = stack.pop()
  874. res = value1 % value2
  875. stack.append(res)
  876. elif opcode == 214: # setlocal_2
  877. registers[2] = stack.pop()
  878. elif opcode == 215: # setlocal_3
  879. registers[3] = stack.pop()
  880. else:
  881. raise NotImplementedError(
  882. u'Unsupported opcode %d' % opcode)
  883. method_pyfunctions[func_name] = resfunc
  884. return resfunc
  885. initial_function = extract_function(u'decipher')
  886. return lambda s: initial_function([s])
  887. def _decrypt_signature(self, s, video_id, jsplayer_url, age_gate=False):
  888. """Turn the encrypted s field into a working signature"""
  889. if jsplayer_url is not None:
  890. try:
  891. if jsplayer_url not in self._jsplayer_cache:
  892. self._jsplayer_cache[jsplayer_url] = self._extract_signature_function(
  893. video_id, jsplayer_url
  894. )
  895. return self._jsplayer_cache[jsplayer_url]([s])
  896. except Exception as e:
  897. tb = traceback.format_exc()
  898. self._downloader.report_warning(u'Automatic signature extraction failed: ' + tb)
  899. self._downloader.report_warning(u'Warning: Falling back to static signature algorithm')
  900. if age_gate:
  901. # The videos with age protection use another player, so the
  902. # algorithms can be different.
  903. if len(s) == 86:
  904. return s[2:63] + s[82] + s[64:82] + s[63]
  905. if len(s) == 92:
  906. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  907. elif len(s) == 90:
  908. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  909. elif len(s) == 89:
  910. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  911. elif len(s) == 88:
  912. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  913. elif len(s) == 87:
  914. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  915. elif len(s) == 86:
  916. 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]
  917. elif len(s) == 85:
  918. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  919. elif len(s) == 84:
  920. return s[81:36:-1] + s[0] + s[35:2:-1]
  921. elif len(s) == 83:
  922. 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]
  923. elif len(s) == 82:
  924. 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]
  925. elif len(s) == 81:
  926. 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]
  927. elif len(s) == 80:
  928. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  929. elif len(s) == 79:
  930. 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]
  931. else:
  932. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  933. def _decrypt_signature_age_gate(self, s):
  934. # The videos with age protection use another player, so the algorithms
  935. # can be different.
  936. if len(s) == 86:
  937. return s[2:63] + s[82] + s[64:82] + s[63]
  938. else:
  939. # Fallback to the other algortihms
  940. return self._decrypt_signature(s)
  941. def _get_available_subtitles(self, video_id):
  942. try:
  943. sub_list = self._download_webpage(
  944. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  945. video_id, note=False)
  946. except ExtractorError as err:
  947. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  948. return {}
  949. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  950. sub_lang_list = {}
  951. for l in lang_list:
  952. lang = l[1]
  953. params = compat_urllib_parse.urlencode({
  954. 'lang': lang,
  955. 'v': video_id,
  956. 'fmt': self._downloader.params.get('subtitlesformat'),
  957. })
  958. url = u'http://www.youtube.com/api/timedtext?' + params
  959. sub_lang_list[lang] = url
  960. if not sub_lang_list:
  961. self._downloader.report_warning(u'video doesn\'t have subtitles')
  962. return {}
  963. return sub_lang_list
  964. def _get_available_automatic_caption(self, video_id, webpage):
  965. """We need the webpage for getting the captions url, pass it as an
  966. argument to speed up the process."""
  967. sub_format = self._downloader.params.get('subtitlesformat')
  968. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  969. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  970. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  971. if mobj is None:
  972. self._downloader.report_warning(err_msg)
  973. return {}
  974. player_config = json.loads(mobj.group(1))
  975. try:
  976. args = player_config[u'args']
  977. caption_url = args[u'ttsurl']
  978. timestamp = args[u'timestamp']
  979. # We get the available subtitles
  980. list_params = compat_urllib_parse.urlencode({
  981. 'type': 'list',
  982. 'tlangs': 1,
  983. 'asrs': 1,
  984. })
  985. list_url = caption_url + '&' + list_params
  986. list_page = self._download_webpage(list_url, video_id)
  987. caption_list = xml.etree.ElementTree.fromstring(list_page.encode('utf-8'))
  988. original_lang_node = caption_list.find('track')
  989. if original_lang_node.attrib.get('kind') != 'asr' :
  990. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  991. return {}
  992. original_lang = original_lang_node.attrib['lang_code']
  993. sub_lang_list = {}
  994. for lang_node in caption_list.findall('target'):
  995. sub_lang = lang_node.attrib['lang_code']
  996. params = compat_urllib_parse.urlencode({
  997. 'lang': original_lang,
  998. 'tlang': sub_lang,
  999. 'fmt': sub_format,
  1000. 'ts': timestamp,
  1001. 'kind': 'asr',
  1002. })
  1003. sub_lang_list[sub_lang] = caption_url + '&' + params
  1004. return sub_lang_list
  1005. # An extractor error can be raise by the download process if there are
  1006. # no automatic captions but there are subtitles
  1007. except (KeyError, ExtractorError):
  1008. self._downloader.report_warning(err_msg)
  1009. return {}
  1010. def _print_formats(self, formats):
  1011. print('Available formats:')
  1012. for x in formats:
  1013. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  1014. self._video_dimensions.get(x, '???'),
  1015. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  1016. def _extract_id(self, url):
  1017. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1018. if mobj is None:
  1019. raise ExtractorError(u'Invalid URL: %s' % url)
  1020. video_id = mobj.group(2)
  1021. return video_id
  1022. def _get_video_url_list(self, url_map):
  1023. """
  1024. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  1025. with the requested formats.
  1026. """
  1027. req_format = self._downloader.params.get('format', None)
  1028. format_limit = self._downloader.params.get('format_limit', None)
  1029. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  1030. if format_limit is not None and format_limit in available_formats:
  1031. format_list = available_formats[available_formats.index(format_limit):]
  1032. else:
  1033. format_list = available_formats
  1034. existing_formats = [x for x in format_list if x in url_map]
  1035. if len(existing_formats) == 0:
  1036. raise ExtractorError(u'no known formats available for video')
  1037. if self._downloader.params.get('listformats', None):
  1038. self._print_formats(existing_formats)
  1039. return
  1040. if req_format is None or req_format == 'best':
  1041. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1042. elif req_format == 'worst':
  1043. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  1044. elif req_format in ('-1', 'all'):
  1045. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1046. else:
  1047. # Specific formats. We pick the first in a slash-delimeted sequence.
  1048. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  1049. # available in the specified format. For example,
  1050. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1051. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  1052. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  1053. req_formats = req_format.split('/')
  1054. video_url_list = None
  1055. for rf in req_formats:
  1056. if rf in url_map:
  1057. video_url_list = [(rf, url_map[rf])]
  1058. break
  1059. if rf in self._video_formats_map:
  1060. for srf in self._video_formats_map[rf]:
  1061. if srf in url_map:
  1062. video_url_list = [(srf, url_map[srf])]
  1063. break
  1064. else:
  1065. continue
  1066. break
  1067. if video_url_list is None:
  1068. raise ExtractorError(u'requested format not available')
  1069. return video_url_list
  1070. def _extract_from_m3u8(self, manifest_url, video_id):
  1071. url_map = {}
  1072. def _get_urls(_manifest):
  1073. lines = _manifest.split('\n')
  1074. urls = filter(lambda l: l and not l.startswith('#'),
  1075. lines)
  1076. return urls
  1077. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  1078. formats_urls = _get_urls(manifest)
  1079. for format_url in formats_urls:
  1080. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1081. url_map[itag] = format_url
  1082. return url_map
  1083. def _real_extract(self, url):
  1084. if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
  1085. 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 ).')
  1086. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1087. mobj = re.search(self._NEXT_URL_RE, url)
  1088. if mobj:
  1089. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  1090. video_id = self._extract_id(url)
  1091. # Get video webpage
  1092. self.report_video_webpage_download(video_id)
  1093. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  1094. request = compat_urllib_request.Request(url)
  1095. try:
  1096. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  1097. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1098. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  1099. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  1100. # Attempt to extract SWF player URL
  1101. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1102. if mobj is not None:
  1103. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1104. else:
  1105. player_url = None
  1106. # Get video info
  1107. self.report_video_info_webpage_download(video_id)
  1108. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1109. self.report_age_confirmation()
  1110. age_gate = True
  1111. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1112. # this can be viewed without login into Youtube
  1113. data = compat_urllib_parse.urlencode({'video_id': video_id,
  1114. 'el': 'embedded',
  1115. 'gl': 'US',
  1116. 'hl': 'en',
  1117. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1118. 'asv': 3,
  1119. 'sts':'1588',
  1120. })
  1121. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  1122. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1123. note=False,
  1124. errnote='unable to download video info webpage')
  1125. video_info = compat_parse_qs(video_info_webpage)
  1126. else:
  1127. age_gate = False
  1128. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1129. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1130. % (video_id, el_type))
  1131. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1132. note=False,
  1133. errnote='unable to download video info webpage')
  1134. video_info = compat_parse_qs(video_info_webpage)
  1135. if 'token' in video_info:
  1136. break
  1137. if 'token' not in video_info:
  1138. if 'reason' in video_info:
  1139. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  1140. else:
  1141. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  1142. # Check for "rental" videos
  1143. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1144. raise ExtractorError(u'"rental" videos not supported')
  1145. # Start extracting information
  1146. self.report_information_extraction(video_id)
  1147. # uploader
  1148. if 'author' not in video_info:
  1149. raise ExtractorError(u'Unable to extract uploader name')
  1150. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1151. # uploader_id
  1152. video_uploader_id = None
  1153. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1154. if mobj is not None:
  1155. video_uploader_id = mobj.group(1)
  1156. else:
  1157. self._downloader.report_warning(u'unable to extract uploader nickname')
  1158. # title
  1159. if 'title' not in video_info:
  1160. raise ExtractorError(u'Unable to extract video title')
  1161. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  1162. # thumbnail image
  1163. # We try first to get a high quality image:
  1164. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1165. video_webpage, re.DOTALL)
  1166. if m_thumb is not None:
  1167. video_thumbnail = m_thumb.group(1)
  1168. elif 'thumbnail_url' not in video_info:
  1169. self._downloader.report_warning(u'unable to extract video thumbnail')
  1170. video_thumbnail = ''
  1171. else: # don't panic if we can't find it
  1172. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1173. # upload date
  1174. upload_date = None
  1175. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1176. if mobj is not None:
  1177. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1178. upload_date = unified_strdate(upload_date)
  1179. # description
  1180. video_description = get_element_by_id("eow-description", video_webpage)
  1181. if video_description:
  1182. video_description = clean_html(video_description)
  1183. else:
  1184. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1185. if fd_mobj:
  1186. video_description = unescapeHTML(fd_mobj.group(1))
  1187. else:
  1188. video_description = u''
  1189. # subtitles
  1190. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1191. if self._downloader.params.get('listsubtitles', False):
  1192. self._list_available_subtitles(video_id, video_webpage)
  1193. return
  1194. if 'length_seconds' not in video_info:
  1195. self._downloader.report_warning(u'unable to extract video duration')
  1196. video_duration = ''
  1197. else:
  1198. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  1199. # Decide which formats to download
  1200. try:
  1201. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  1202. if not mobj:
  1203. raise ValueError('Could not find vevo ID')
  1204. info = json.loads(mobj.group(1))
  1205. args = info['args']
  1206. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1207. # this signatures are encrypted
  1208. m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
  1209. if m_s is not None:
  1210. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1211. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1212. m_s = re.search(r'[&,]s=', args.get('adaptive_fmts', u''))
  1213. if m_s is not None:
  1214. if 'url_encoded_fmt_stream_map' in video_info:
  1215. video_info['url_encoded_fmt_stream_map'][0] += ',' + args['adaptive_fmts']
  1216. else:
  1217. video_info['url_encoded_fmt_stream_map'] = [args['adaptive_fmts']]
  1218. elif 'adaptive_fmts' in video_info:
  1219. if 'url_encoded_fmt_stream_map' in video_info:
  1220. video_info['url_encoded_fmt_stream_map'][0] += ',' + video_info['adaptive_fmts'][0]
  1221. else:
  1222. video_info['url_encoded_fmt_stream_map'] = video_info['adaptive_fmts']
  1223. except ValueError:
  1224. pass
  1225. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1226. self.report_rtmp_download()
  1227. video_url_list = [(None, video_info['conn'][0])]
  1228. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  1229. if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
  1230. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1231. url_map = {}
  1232. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  1233. url_data = compat_parse_qs(url_data_str)
  1234. if 'itag' in url_data and 'url' in url_data:
  1235. url = url_data['url'][0]
  1236. if 'sig' in url_data:
  1237. url += '&signature=' + url_data['sig'][0]
  1238. elif 's' in url_data:
  1239. encrypted_sig = url_data['s'][0]
  1240. if self._downloader.params.get('verbose'):
  1241. if age_gate:
  1242. player_version = self._search_regex(r'-(.+)\.swf$',
  1243. player_url if player_url else 'NOT FOUND',
  1244. 'flash player', fatal=False)
  1245. player_desc = 'flash player %s' % player_version
  1246. else:
  1247. player_version = self._search_regex(r'html5player-(.+?)\.js', video_webpage,
  1248. 'html5 player', fatal=False)
  1249. player_desc = u'html5 player %s' % player_version
  1250. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1251. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1252. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1253. if age_gate:
  1254. jsplayer_url = None
  1255. else:
  1256. jsplayer_url_json = self._search_regex(
  1257. r'"assets":.+?"js":\s*("[^"]+")',
  1258. video_webpage, u'JS player URL')
  1259. jsplayer_url = json.loads(jsplayer_url_json)
  1260. signature = self._decrypt_signature(encrypted_sig, video_id, jsplayer_url, age_gate)
  1261. url += '&signature=' + signature
  1262. if 'ratebypass' not in url:
  1263. url += '&ratebypass=yes'
  1264. url_map[url_data['itag'][0]] = url
  1265. video_url_list = self._get_video_url_list(url_map)
  1266. if not video_url_list:
  1267. return
  1268. elif video_info.get('hlsvp'):
  1269. manifest_url = video_info['hlsvp'][0]
  1270. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1271. video_url_list = self._get_video_url_list(url_map)
  1272. if not video_url_list:
  1273. return
  1274. else:
  1275. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  1276. results = []
  1277. for format_param, video_real_url in video_url_list:
  1278. # Extension
  1279. video_extension = self._video_extensions.get(format_param, 'flv')
  1280. video_format = '{0} - {1}{2}'.format(format_param if format_param else video_extension,
  1281. self._video_dimensions.get(format_param, '???'),
  1282. ' ('+self._special_itags[format_param]+')' if format_param in self._special_itags else '')
  1283. results.append({
  1284. 'id': video_id,
  1285. 'url': video_real_url,
  1286. 'uploader': video_uploader,
  1287. 'uploader_id': video_uploader_id,
  1288. 'upload_date': upload_date,
  1289. 'title': video_title,
  1290. 'ext': video_extension,
  1291. 'format': video_format,
  1292. 'thumbnail': video_thumbnail,
  1293. 'description': video_description,
  1294. 'player_url': player_url,
  1295. 'subtitles': video_subtitles,
  1296. 'duration': video_duration
  1297. })
  1298. return results
  1299. class YoutubePlaylistIE(InfoExtractor):
  1300. IE_DESC = u'YouTube.com playlists'
  1301. _VALID_URL = r"""(?:
  1302. (?:https?://)?
  1303. (?:\w+\.)?
  1304. youtube\.com/
  1305. (?:
  1306. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1307. \? (?:.*?&)*? (?:p|a|list)=
  1308. | p/
  1309. )
  1310. ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
  1311. .*
  1312. |
  1313. ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
  1314. )"""
  1315. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  1316. _MAX_RESULTS = 50
  1317. IE_NAME = u'youtube:playlist'
  1318. @classmethod
  1319. def suitable(cls, url):
  1320. """Receives a URL and returns True if suitable for this IE."""
  1321. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1322. def _real_extract(self, url):
  1323. # Extract playlist id
  1324. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1325. if mobj is None:
  1326. raise ExtractorError(u'Invalid URL: %s' % url)
  1327. # Download playlist videos from API
  1328. playlist_id = mobj.group(1) or mobj.group(2)
  1329. videos = []
  1330. for page_num in itertools.count(1):
  1331. start_index = self._MAX_RESULTS * (page_num - 1) + 1
  1332. if start_index >= 1000:
  1333. self._downloader.report_warning(u'Max number of results reached')
  1334. break
  1335. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, start_index)
  1336. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1337. try:
  1338. response = json.loads(page)
  1339. except ValueError as err:
  1340. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1341. if 'feed' not in response:
  1342. raise ExtractorError(u'Got a malformed response from YouTube API')
  1343. playlist_title = response['feed']['title']['$t']
  1344. if 'entry' not in response['feed']:
  1345. # Number of videos is a multiple of self._MAX_RESULTS
  1346. break
  1347. for entry in response['feed']['entry']:
  1348. index = entry['yt$position']['$t']
  1349. if 'media$group' in entry and 'yt$videoid' in entry['media$group']:
  1350. videos.append((
  1351. index,
  1352. 'https://www.youtube.com/watch?v=' + entry['media$group']['yt$videoid']['$t']
  1353. ))
  1354. videos = [v[1] for v in sorted(videos)]
  1355. url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
  1356. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  1357. class YoutubeChannelIE(InfoExtractor):
  1358. IE_DESC = u'YouTube.com channels'
  1359. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1360. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1361. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1362. _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'
  1363. IE_NAME = u'youtube:channel'
  1364. def extract_videos_from_page(self, page):
  1365. ids_in_page = []
  1366. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1367. if mobj.group(1) not in ids_in_page:
  1368. ids_in_page.append(mobj.group(1))
  1369. return ids_in_page
  1370. def _real_extract(self, url):
  1371. # Extract channel id
  1372. mobj = re.match(self._VALID_URL, url)
  1373. if mobj is None:
  1374. raise ExtractorError(u'Invalid URL: %s' % url)
  1375. # Download channel page
  1376. channel_id = mobj.group(1)
  1377. video_ids = []
  1378. pagenum = 1
  1379. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1380. page = self._download_webpage(url, channel_id,
  1381. u'Downloading page #%s' % pagenum)
  1382. # Extract video identifiers
  1383. ids_in_page = self.extract_videos_from_page(page)
  1384. video_ids.extend(ids_in_page)
  1385. # Download any subsequent channel pages using the json-based channel_ajax query
  1386. if self._MORE_PAGES_INDICATOR in page:
  1387. for pagenum in itertools.count(1):
  1388. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1389. page = self._download_webpage(url, channel_id,
  1390. u'Downloading page #%s' % pagenum)
  1391. page = json.loads(page)
  1392. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1393. video_ids.extend(ids_in_page)
  1394. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1395. break
  1396. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1397. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  1398. url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
  1399. return [self.playlist_result(url_entries, channel_id)]
  1400. class YoutubeUserIE(InfoExtractor):
  1401. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1402. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?)|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1403. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1404. _GDATA_PAGE_SIZE = 50
  1405. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1406. IE_NAME = u'youtube:user'
  1407. @classmethod
  1408. def suitable(cls, url):
  1409. # Don't return True if the url can be extracted with other youtube
  1410. # extractor, the regex would is too permissive and it would match.
  1411. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1412. if any(ie.suitable(url) for ie in other_ies): return False
  1413. else: return super(YoutubeUserIE, cls).suitable(url)
  1414. def _real_extract(self, url):
  1415. # Extract username
  1416. mobj = re.match(self._VALID_URL, url)
  1417. if mobj is None:
  1418. raise ExtractorError(u'Invalid URL: %s' % url)
  1419. username = mobj.group(1)
  1420. # Download video ids using YouTube Data API. Result size per
  1421. # query is limited (currently to 50 videos) so we need to query
  1422. # page by page until there are no video ids - it means we got
  1423. # all of them.
  1424. video_ids = []
  1425. for pagenum in itertools.count(0):
  1426. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1427. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1428. page = self._download_webpage(gdata_url, username,
  1429. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  1430. try:
  1431. response = json.loads(page)
  1432. except ValueError as err:
  1433. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1434. if 'entry' not in response['feed']:
  1435. # Number of videos is a multiple of self._MAX_RESULTS
  1436. break
  1437. # Extract video identifiers
  1438. ids_in_page = []
  1439. for entry in response['feed']['entry']:
  1440. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  1441. video_ids.extend(ids_in_page)
  1442. # A little optimization - if current page is not
  1443. # "full", ie. does not contain PAGE_SIZE video ids then
  1444. # we can assume that this page is the last one - there
  1445. # are no more ids on further pages - no need to query
  1446. # again.
  1447. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1448. break
  1449. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  1450. url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
  1451. return [self.playlist_result(url_results, playlist_title = username)]
  1452. class YoutubeSearchIE(SearchInfoExtractor):
  1453. IE_DESC = u'YouTube.com searches'
  1454. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1455. _MAX_RESULTS = 1000
  1456. IE_NAME = u'youtube:search'
  1457. _SEARCH_KEY = 'ytsearch'
  1458. def report_download_page(self, query, pagenum):
  1459. """Report attempt to download search page with given number."""
  1460. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1461. def _get_n_results(self, query, n):
  1462. """Get a specified number of results for a query"""
  1463. video_ids = []
  1464. pagenum = 0
  1465. limit = n
  1466. while (50 * pagenum) < limit:
  1467. self.report_download_page(query, pagenum+1)
  1468. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1469. request = compat_urllib_request.Request(result_url)
  1470. try:
  1471. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1472. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1473. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  1474. api_response = json.loads(data)['data']
  1475. if not 'items' in api_response:
  1476. raise ExtractorError(u'[youtube] No video results')
  1477. new_ids = list(video['id'] for video in api_response['items'])
  1478. video_ids += new_ids
  1479. limit = min(n, api_response['totalItems'])
  1480. pagenum += 1
  1481. if len(video_ids) > n:
  1482. video_ids = video_ids[:n]
  1483. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  1484. return self.playlist_result(videos, query)
  1485. class YoutubeShowIE(InfoExtractor):
  1486. IE_DESC = u'YouTube.com (multi-season) shows'
  1487. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1488. IE_NAME = u'youtube:show'
  1489. def _real_extract(self, url):
  1490. mobj = re.match(self._VALID_URL, url)
  1491. show_name = mobj.group(1)
  1492. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1493. # There's one playlist for each season of the show
  1494. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1495. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1496. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1497. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1498. """
  1499. Base class for extractors that fetch info from
  1500. http://www.youtube.com/feed_ajax
  1501. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1502. """
  1503. _LOGIN_REQUIRED = True
  1504. _PAGING_STEP = 30
  1505. # use action_load_personal_feed instead of action_load_system_feed
  1506. _PERSONAL_FEED = False
  1507. @property
  1508. def _FEED_TEMPLATE(self):
  1509. action = 'action_load_system_feed'
  1510. if self._PERSONAL_FEED:
  1511. action = 'action_load_personal_feed'
  1512. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1513. @property
  1514. def IE_NAME(self):
  1515. return u'youtube:%s' % self._FEED_NAME
  1516. def _real_initialize(self):
  1517. self._login()
  1518. def _real_extract(self, url):
  1519. feed_entries = []
  1520. # The step argument is available only in 2.7 or higher
  1521. for i in itertools.count(0):
  1522. paging = i*self._PAGING_STEP
  1523. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  1524. u'%s feed' % self._FEED_NAME,
  1525. u'Downloading page %s' % i)
  1526. info = json.loads(info)
  1527. feed_html = info['feed_html']
  1528. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1529. ids = orderedSet(m.group(1) for m in m_ids)
  1530. feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
  1531. if info['paging'] is None:
  1532. break
  1533. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1534. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1535. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1536. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1537. _FEED_NAME = 'subscriptions'
  1538. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1539. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1540. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1541. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1542. _FEED_NAME = 'recommended'
  1543. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1544. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1545. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1546. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1547. _FEED_NAME = 'watch_later'
  1548. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1549. _PAGING_STEP = 100
  1550. _PERSONAL_FEED = True
  1551. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1552. IE_NAME = u'youtube:favorites'
  1553. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1554. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1555. _LOGIN_REQUIRED = True
  1556. def _real_extract(self, url):
  1557. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1558. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1559. return self.url_result(playlist_id, 'YoutubePlaylist')