youtube.py 76 KB

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