youtube.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  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._player_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>[a-zA-Z0-9]+)\.(?P<ext>[a-z]+)$',
  399. player_url)
  400. player_type = id_m.group('ext')
  401. player_id = id_m.group('id')
  402. # TODO read from filesystem cache
  403. if player_type == 'js':
  404. code = self._download_webpage(
  405. player_url, video_id,
  406. note=u'Downloading %s player %s' % (player_type, player_id),
  407. errnote=u'Download of %s failed' % player_url)
  408. res = self._parse_sig_js(code)
  409. elif player_tpye == 'swf':
  410. urlh = self._request_webpage(
  411. player_url, video_id,
  412. note=u'Downloading %s player %s' % (player_type, player_id),
  413. errnote=u'Download of %s failed' % player_url)
  414. code = urlh.read()
  415. res = self._parse_sig_swf(code)
  416. else:
  417. assert False, 'Invalid player type %r' % player_type
  418. # TODO write cache
  419. return res
  420. def _parse_sig_js(self, jscode):
  421. funcname = self._search_regex(
  422. r'signature=([a-zA-Z]+)', jscode,
  423. u'Initial JS player signature function name')
  424. functions = {}
  425. def argidx(varname):
  426. return string.lowercase.index(varname)
  427. def interpret_statement(stmt, local_vars, allow_recursion=20):
  428. if allow_recursion < 0:
  429. raise ExctractorError(u'Recursion limit reached')
  430. if stmt.startswith(u'var '):
  431. stmt = stmt[len(u'var '):]
  432. ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
  433. r'=(?P<expr>.*)$', stmt)
  434. if ass_m:
  435. if ass_m.groupdict().get('index'):
  436. def assign(val):
  437. lvar = local_vars[ass_m.group('out')]
  438. idx = interpret_expression(ass_m.group('index'),
  439. local_vars, allow_recursion)
  440. assert isinstance(idx, int)
  441. lvar[idx] = val
  442. return val
  443. expr = ass_m.group('expr')
  444. else:
  445. def assign(val):
  446. local_vars[ass_m.group('out')] = val
  447. return val
  448. expr = ass_m.group('expr')
  449. elif stmt.startswith(u'return '):
  450. assign = lambda v: v
  451. expr = stmt[len(u'return '):]
  452. else:
  453. raise ExtractorError(
  454. u'Cannot determine left side of statement in %r' % stmt)
  455. v = interpret_expression(expr, local_vars, allow_recursion)
  456. return assign(v)
  457. def interpret_expression(expr, local_vars, allow_recursion):
  458. if expr.isdigit():
  459. return int(expr)
  460. if expr.isalpha():
  461. return local_vars[expr]
  462. m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
  463. if m:
  464. member = m.group('member')
  465. val = local_vars[m.group('in')]
  466. if member == 'split("")':
  467. return list(val)
  468. if member == 'join("")':
  469. return u''.join(val)
  470. if member == 'length':
  471. return len(val)
  472. if member == 'reverse()':
  473. return val[::-1]
  474. slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
  475. if slice_m:
  476. idx = interpret_expression(
  477. slice_m.group('idx'), local_vars, allow_recursion-1)
  478. return val[idx:]
  479. m = re.match(
  480. r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
  481. if m:
  482. val = local_vars[m.group('in')]
  483. idx = interpret_expression(m.group('idx'), local_vars,
  484. allow_recursion-1)
  485. return val[idx]
  486. m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
  487. if m:
  488. a = interpret_expression(m.group('a'),
  489. local_vars, allow_recursion)
  490. b = interpret_expression(m.group('b'),
  491. local_vars, allow_recursion)
  492. return a % b
  493. m = re.match(
  494. r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
  495. if m:
  496. fname = m.group('func')
  497. if fname not in functions:
  498. functions[fname] = extract_function(fname)
  499. argvals = [int(v) if v.isdigit() else local_vars[v]
  500. for v in m.group('args').split(',')]
  501. return functions[fname](argvals)
  502. raise ExtractorError(u'Unsupported JS expression %r' % expr)
  503. def extract_function(funcname):
  504. func_m = re.search(
  505. r'function ' + re.escape(funcname) +
  506. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  507. jscode)
  508. argnames = func_m.group('args').split(',')
  509. def resf(args):
  510. local_vars = dict(zip(argnames, args))
  511. for stmt in func_m.group('code').split(';'):
  512. res = interpret_statement(stmt, local_vars)
  513. return res
  514. return resf
  515. initial_function = extract_function(funcname)
  516. return lambda s: initial_function([s])
  517. def _parse_sig_swf(self, file_contents):
  518. if file_contents[1:3] != b'WS':
  519. raise ExtractorError(
  520. u'Not an SWF file; header is %r' % file_contents[:3])
  521. if file_contents[:1] == b'C':
  522. content = zlib.decompress(file_contents[8:])
  523. else:
  524. raise NotImplementedError(u'Unsupported compression format %r' %
  525. file_contents[:1])
  526. def extract_tags(content):
  527. pos = 0
  528. while pos < len(content):
  529. header16 = struct.unpack('<H', content[pos:pos+2])[0]
  530. pos += 2
  531. tag_code = header16 >> 6
  532. tag_len = header16 & 0x3f
  533. if tag_len == 0x3f:
  534. tag_len = struct.unpack('<I', content[pos:pos+4])[0]
  535. pos += 4
  536. assert pos+tag_len <= len(content)
  537. yield (tag_code, content[pos:pos+tag_len])
  538. pos += tag_len
  539. code_tag = next(tag
  540. for tag_code, tag in extract_tags(content)
  541. if tag_code == 82)
  542. p = code_tag.index(b'\0', 4) + 1
  543. code_reader = io.BytesIO(code_tag[p:])
  544. # Parse ABC (AVM2 ByteCode)
  545. def read_int(reader=None):
  546. if reader is None:
  547. reader = code_reader
  548. res = 0
  549. shift = 0
  550. for _ in range(5):
  551. buf = reader.read(1)
  552. assert len(buf) == 1
  553. b = struct.unpack('<B', buf)[0]
  554. res = res | ((b & 0x7f) << shift)
  555. if b & 0x80 == 0:
  556. break
  557. shift += 7
  558. return res
  559. def u30(reader=None):
  560. res = read_int(reader)
  561. assert res & 0xf0000000 == 0
  562. return res
  563. u32 = read_int
  564. def s32(reader=None):
  565. v = read_int(reader)
  566. if v & 0x80000000 != 0:
  567. v = - ((v ^ 0xffffffff) + 1)
  568. return v
  569. def string(reader=None):
  570. if reader is None:
  571. reader = code_reader
  572. slen = u30(reader)
  573. resb = reader.read(slen)
  574. assert len(resb) == slen
  575. return resb.decode('utf-8')
  576. def read_bytes(count, reader=None):
  577. if reader is None:
  578. reader = code_reader
  579. resb = reader.read(count)
  580. assert len(resb) == count
  581. return resb
  582. def read_byte(reader=None):
  583. resb = read_bytes(1, reader=reader)
  584. res = struct.unpack('<B', resb)[0]
  585. return res
  586. # minor_version + major_version
  587. _ = read_bytes(2 + 2)
  588. # Constant pool
  589. int_count = u30()
  590. for _c in range(1, int_count):
  591. _ = s32()
  592. uint_count = u30()
  593. for _c in range(1, uint_count):
  594. _ = u32()
  595. double_count = u30()
  596. _ = read_bytes((double_count-1) * 8)
  597. string_count = u30()
  598. constant_strings = [u'']
  599. for _c in range(1, string_count):
  600. s = string()
  601. constant_strings.append(s)
  602. namespace_count = u30()
  603. for _c in range(1, namespace_count):
  604. _ = read_bytes(1) # kind
  605. _ = u30() # name
  606. ns_set_count = u30()
  607. for _c in range(1, ns_set_count):
  608. count = u30()
  609. for _c2 in range(count):
  610. _ = u30()
  611. multiname_count = u30()
  612. MULTINAME_SIZES = {
  613. 0x07: 2, # QName
  614. 0x0d: 2, # QNameA
  615. 0x0f: 1, # RTQName
  616. 0x10: 1, # RTQNameA
  617. 0x11: 0, # RTQNameL
  618. 0x12: 0, # RTQNameLA
  619. 0x09: 2, # Multiname
  620. 0x0e: 2, # MultinameA
  621. 0x1b: 1, # MultinameL
  622. 0x1c: 1, # MultinameLA
  623. }
  624. multinames = [u'']
  625. for _c in range(1, multiname_count):
  626. kind = u30()
  627. assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
  628. if kind == 0x07:
  629. namespace_idx = u30()
  630. name_idx = u30()
  631. multinames.append(constant_strings[name_idx])
  632. else:
  633. multinames.append('[MULTINAME kind: %d]' % kind)
  634. for _c2 in range(MULTINAME_SIZES[kind]):
  635. _ = u30()
  636. # Methods
  637. method_count = u30()
  638. MethodInfo = collections.namedtuple(
  639. 'MethodInfo',
  640. ['NEED_ARGUMENTS', 'NEED_REST'])
  641. method_infos = []
  642. for method_id in range(method_count):
  643. param_count = u30()
  644. _ = u30() # return type
  645. for _ in range(param_count):
  646. _ = u30() # param type
  647. _ = u30() # name index (always 0 for youtube)
  648. flags = read_byte()
  649. if flags & 0x08 != 0:
  650. # Options present
  651. option_count = u30()
  652. for c in range(option_count):
  653. _ = u30() # val
  654. _ = read_bytes(1) # kind
  655. if flags & 0x80 != 0:
  656. # Param names present
  657. for _ in range(param_count):
  658. _ = u30() # param name
  659. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  660. method_infos.append(mi)
  661. # Metadata
  662. metadata_count = u30()
  663. for _c in range(metadata_count):
  664. _ = u30() # name
  665. item_count = u30()
  666. for _c2 in range(item_count):
  667. _ = u30() # key
  668. _ = u30() # value
  669. def parse_traits_info():
  670. trait_name_idx = u30()
  671. kind_full = read_byte()
  672. kind = kind_full & 0x0f
  673. attrs = kind_full >> 4
  674. methods = {}
  675. if kind in [0x00, 0x06]: # Slot or Const
  676. _ = u30() # Slot id
  677. type_name_idx = u30()
  678. vindex = u30()
  679. if vindex != 0:
  680. _ = read_byte() # vkind
  681. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  682. _ = u30() # disp_id
  683. method_idx = u30()
  684. methods[multinames[trait_name_idx]] = method_idx
  685. elif kind == 0x04: # Class
  686. _ = u30() # slot_id
  687. _ = u30() # classi
  688. elif kind == 0x05: # Function
  689. _ = u30() # slot_id
  690. function_idx = u30()
  691. methods[function_idx] = multinames[trait_name_idx]
  692. else:
  693. raise ExtractorError(u'Unsupported trait kind %d' % kind)
  694. if attrs & 0x4 != 0: # Metadata present
  695. metadata_count = u30()
  696. for _c3 in range(metadata_count):
  697. _ = u30()
  698. return methods
  699. # Classes
  700. TARGET_CLASSNAME = u'SignatureDecipher'
  701. searched_idx = multinames.index(TARGET_CLASSNAME)
  702. searched_class_id = None
  703. class_count = u30()
  704. for class_id in range(class_count):
  705. name_idx = u30()
  706. if name_idx == searched_idx:
  707. # We found the class we're looking for!
  708. searched_class_id = class_id
  709. _ = u30() # super_name idx
  710. flags = read_byte()
  711. if flags & 0x08 != 0: # Protected namespace is present
  712. protected_ns_idx = u30()
  713. intrf_count = u30()
  714. for _c2 in range(intrf_count):
  715. _ = u30()
  716. _ = u30() # iinit
  717. trait_count = u30()
  718. for _c2 in range(trait_count):
  719. _ = parse_traits_info()
  720. if searched_class_id is None:
  721. raise ExtractorError(u'Target class %r not found' %
  722. TARGET_CLASSNAME)
  723. method_names = {}
  724. method_idxs = {}
  725. for class_id in range(class_count):
  726. _ = u30() # cinit
  727. trait_count = u30()
  728. for _c2 in range(trait_count):
  729. trait_methods = parse_traits_info()
  730. if class_id == searched_class_id:
  731. method_names.update(trait_methods.items())
  732. method_idxs.update(dict(
  733. (idx, name)
  734. for name, idx in trait_methods.items()))
  735. # Scripts
  736. script_count = u30()
  737. for _c in range(script_count):
  738. _ = u30() # init
  739. trait_count = u30()
  740. for _c2 in range(trait_count):
  741. _ = parse_traits_info()
  742. # Method bodies
  743. method_body_count = u30()
  744. Method = collections.namedtuple('Method', ['code', 'local_count'])
  745. methods = {}
  746. for _c in range(method_body_count):
  747. method_idx = u30()
  748. max_stack = u30()
  749. local_count = u30()
  750. init_scope_depth = u30()
  751. max_scope_depth = u30()
  752. code_length = u30()
  753. code = read_bytes(code_length)
  754. if method_idx in method_idxs:
  755. m = Method(code, local_count)
  756. methods[method_idxs[method_idx]] = m
  757. exception_count = u30()
  758. for _c2 in range(exception_count):
  759. _ = u30() # from
  760. _ = u30() # to
  761. _ = u30() # target
  762. _ = u30() # exc_type
  763. _ = u30() # var_name
  764. trait_count = u30()
  765. for _c2 in range(trait_count):
  766. _ = parse_traits_info()
  767. assert p + code_reader.tell() == len(code_tag)
  768. assert len(methods) == len(method_idxs)
  769. method_pyfunctions = {}
  770. def extract_function(func_name):
  771. if func_name in method_pyfunctions:
  772. return method_pyfunctions[func_name]
  773. if func_name not in methods:
  774. raise ExtractorError(u'Cannot find function %r' % func_name)
  775. m = methods[func_name]
  776. def resfunc(args):
  777. registers = ['(this)'] + list(args) + [None] * m.local_count
  778. stack = []
  779. coder = io.BytesIO(m.code)
  780. while True:
  781. opcode = struct.unpack('!B', coder.read(1))[0]
  782. if opcode == 36: # pushbyte
  783. v = struct.unpack('!B', coder.read(1))[0]
  784. stack.append(v)
  785. elif opcode == 44: # pushstring
  786. idx = u30(coder)
  787. stack.append(constant_strings[idx])
  788. elif opcode == 48: # pushscope
  789. # We don't implement the scope register, so we'll just
  790. # ignore the popped value
  791. stack.pop()
  792. elif opcode == 70: # callproperty
  793. index = u30(coder)
  794. mname = multinames[index]
  795. arg_count = u30(coder)
  796. args = list(reversed(
  797. [stack.pop() for _ in range(arg_count)]))
  798. obj = stack.pop()
  799. if mname == u'split':
  800. assert len(args) == 1
  801. assert isinstance(args[0], compat_str)
  802. assert isinstance(obj, compat_str)
  803. if args[0] == u'':
  804. res = list(obj)
  805. else:
  806. res = obj.split(args[0])
  807. stack.append(res)
  808. elif mname == u'slice':
  809. assert len(args) == 1
  810. assert isinstance(args[0], int)
  811. assert isinstance(obj, list)
  812. res = obj[args[0]:]
  813. stack.append(res)
  814. elif mname == u'join':
  815. assert len(args) == 1
  816. assert isinstance(args[0], compat_str)
  817. assert isinstance(obj, list)
  818. res = args[0].join(obj)
  819. stack.append(res)
  820. elif mname in method_pyfunctions:
  821. stack.append(method_pyfunctions[mname](args))
  822. else:
  823. raise NotImplementedError(
  824. u'Unsupported property %r on %r'
  825. % (mname, obj))
  826. elif opcode == 72: # returnvalue
  827. res = stack.pop()
  828. return res
  829. elif opcode == 79: # callpropvoid
  830. index = u30(coder)
  831. mname = multinames[index]
  832. arg_count = u30(coder)
  833. args = list(reversed(
  834. [stack.pop() for _ in range(arg_count)]))
  835. obj = stack.pop()
  836. if mname == u'reverse':
  837. assert isinstance(obj, list)
  838. obj.reverse()
  839. else:
  840. raise NotImplementedError(
  841. u'Unsupported (void) property %r on %r'
  842. % (mname, obj))
  843. elif opcode == 93: # findpropstrict
  844. index = u30(coder)
  845. mname = multinames[index]
  846. res = extract_function(mname)
  847. stack.append(res)
  848. elif opcode == 97: # setproperty
  849. index = u30(coder)
  850. value = stack.pop()
  851. idx = stack.pop()
  852. obj = stack.pop()
  853. assert isinstance(obj, list)
  854. assert isinstance(idx, int)
  855. obj[idx] = value
  856. elif opcode == 98: # getlocal
  857. index = u30(coder)
  858. stack.append(registers[index])
  859. elif opcode == 99: # setlocal
  860. index = u30(coder)
  861. value = stack.pop()
  862. registers[index] = value
  863. elif opcode == 102: # getproperty
  864. index = u30(coder)
  865. pname = multinames[index]
  866. if pname == u'length':
  867. obj = stack.pop()
  868. assert isinstance(obj, list)
  869. stack.append(len(obj))
  870. else: # Assume attribute access
  871. idx = stack.pop()
  872. assert isinstance(idx, int)
  873. obj = stack.pop()
  874. assert isinstance(obj, list)
  875. stack.append(obj[idx])
  876. elif opcode == 128: # coerce
  877. _ = u30(coder)
  878. elif opcode == 133: # coerce_s
  879. assert isinstance(stack[-1], (type(None), compat_str))
  880. elif opcode == 164: # modulo
  881. value2 = stack.pop()
  882. value1 = stack.pop()
  883. res = value1 % value2
  884. stack.append(res)
  885. elif opcode == 208: # getlocal_0
  886. stack.append(registers[0])
  887. elif opcode == 209: # getlocal_1
  888. stack.append(registers[1])
  889. elif opcode == 210: # getlocal_2
  890. stack.append(registers[2])
  891. elif opcode == 211: # getlocal_3
  892. stack.append(registers[3])
  893. elif opcode == 214: # setlocal_2
  894. registers[2] = stack.pop()
  895. elif opcode == 215: # setlocal_3
  896. registers[3] = stack.pop()
  897. else:
  898. raise NotImplementedError(
  899. u'Unsupported opcode %d' % opcode)
  900. method_pyfunctions[func_name] = resfunc
  901. return resfunc
  902. initial_function = extract_function(u'decipher')
  903. return lambda s: initial_function([s])
  904. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  905. """Turn the encrypted s field into a working signature"""
  906. if player_url is not None:
  907. try:
  908. if player_url not in self._player_cache:
  909. func = self._extract_signature_function(
  910. video_id, player_url
  911. )
  912. self._player_cache[player_url] = func
  913. return self._player_cache[player_url](s)
  914. except Exception as e:
  915. tb = traceback.format_exc()
  916. self._downloader.report_warning(
  917. u'Automatic signature extraction failed: ' + tb)
  918. self._downloader.report_warning(
  919. u'Warning: Falling back to static signature algorithm')
  920. return self._static_decrypt_signature(
  921. s, video_id, player_url, age_gate)
  922. def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
  923. if age_gate:
  924. # The videos with age protection use another player, so the
  925. # algorithms can be different.
  926. if len(s) == 86:
  927. return s[2:63] + s[82] + s[64:82] + s[63]
  928. if len(s) == 92:
  929. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  930. elif len(s) == 90:
  931. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  932. elif len(s) == 89:
  933. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  934. elif len(s) == 88:
  935. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  936. elif len(s) == 87:
  937. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  938. elif len(s) == 86:
  939. 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]
  940. elif len(s) == 85:
  941. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  942. elif len(s) == 84:
  943. return s[81:36:-1] + s[0] + s[35:2:-1]
  944. elif len(s) == 83:
  945. 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]
  946. elif len(s) == 82:
  947. 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]
  948. elif len(s) == 81:
  949. 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]
  950. elif len(s) == 80:
  951. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  952. elif len(s) == 79:
  953. 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]
  954. else:
  955. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  956. def _decrypt_signature_age_gate(self, s):
  957. # The videos with age protection use another player, so the algorithms
  958. # can be different.
  959. if len(s) == 86:
  960. return s[2:63] + s[82] + s[64:82] + s[63]
  961. else:
  962. # Fallback to the other algortihms
  963. return self._decrypt_signature(s)
  964. def _get_available_subtitles(self, video_id):
  965. try:
  966. sub_list = self._download_webpage(
  967. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  968. video_id, note=False)
  969. except ExtractorError as err:
  970. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  971. return {}
  972. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  973. sub_lang_list = {}
  974. for l in lang_list:
  975. lang = l[1]
  976. params = compat_urllib_parse.urlencode({
  977. 'lang': lang,
  978. 'v': video_id,
  979. 'fmt': self._downloader.params.get('subtitlesformat'),
  980. })
  981. url = u'http://www.youtube.com/api/timedtext?' + params
  982. sub_lang_list[lang] = url
  983. if not sub_lang_list:
  984. self._downloader.report_warning(u'video doesn\'t have subtitles')
  985. return {}
  986. return sub_lang_list
  987. def _get_available_automatic_caption(self, video_id, webpage):
  988. """We need the webpage for getting the captions url, pass it as an
  989. argument to speed up the process."""
  990. sub_format = self._downloader.params.get('subtitlesformat')
  991. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  992. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  993. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  994. if mobj is None:
  995. self._downloader.report_warning(err_msg)
  996. return {}
  997. player_config = json.loads(mobj.group(1))
  998. try:
  999. args = player_config[u'args']
  1000. caption_url = args[u'ttsurl']
  1001. timestamp = args[u'timestamp']
  1002. # We get the available subtitles
  1003. list_params = compat_urllib_parse.urlencode({
  1004. 'type': 'list',
  1005. 'tlangs': 1,
  1006. 'asrs': 1,
  1007. })
  1008. list_url = caption_url + '&' + list_params
  1009. list_page = self._download_webpage(list_url, video_id)
  1010. caption_list = xml.etree.ElementTree.fromstring(list_page.encode('utf-8'))
  1011. original_lang_node = caption_list.find('track')
  1012. if original_lang_node.attrib.get('kind') != 'asr' :
  1013. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  1014. return {}
  1015. original_lang = original_lang_node.attrib['lang_code']
  1016. sub_lang_list = {}
  1017. for lang_node in caption_list.findall('target'):
  1018. sub_lang = lang_node.attrib['lang_code']
  1019. params = compat_urllib_parse.urlencode({
  1020. 'lang': original_lang,
  1021. 'tlang': sub_lang,
  1022. 'fmt': sub_format,
  1023. 'ts': timestamp,
  1024. 'kind': 'asr',
  1025. })
  1026. sub_lang_list[sub_lang] = caption_url + '&' + params
  1027. return sub_lang_list
  1028. # An extractor error can be raise by the download process if there are
  1029. # no automatic captions but there are subtitles
  1030. except (KeyError, ExtractorError):
  1031. self._downloader.report_warning(err_msg)
  1032. return {}
  1033. def _print_formats(self, formats):
  1034. print('Available formats:')
  1035. for x in formats:
  1036. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  1037. self._video_dimensions.get(x, '???'),
  1038. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  1039. def _extract_id(self, url):
  1040. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1041. if mobj is None:
  1042. raise ExtractorError(u'Invalid URL: %s' % url)
  1043. video_id = mobj.group(2)
  1044. return video_id
  1045. def _get_video_url_list(self, url_map):
  1046. """
  1047. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  1048. with the requested formats.
  1049. """
  1050. req_format = self._downloader.params.get('format', None)
  1051. format_limit = self._downloader.params.get('format_limit', None)
  1052. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  1053. if format_limit is not None and format_limit in available_formats:
  1054. format_list = available_formats[available_formats.index(format_limit):]
  1055. else:
  1056. format_list = available_formats
  1057. existing_formats = [x for x in format_list if x in url_map]
  1058. if len(existing_formats) == 0:
  1059. raise ExtractorError(u'no known formats available for video')
  1060. if self._downloader.params.get('listformats', None):
  1061. self._print_formats(existing_formats)
  1062. return
  1063. if req_format is None or req_format == 'best':
  1064. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1065. elif req_format == 'worst':
  1066. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  1067. elif req_format in ('-1', 'all'):
  1068. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1069. else:
  1070. # Specific formats. We pick the first in a slash-delimeted sequence.
  1071. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  1072. # available in the specified format. For example,
  1073. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1074. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  1075. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  1076. req_formats = req_format.split('/')
  1077. video_url_list = None
  1078. for rf in req_formats:
  1079. if rf in url_map:
  1080. video_url_list = [(rf, url_map[rf])]
  1081. break
  1082. if rf in self._video_formats_map:
  1083. for srf in self._video_formats_map[rf]:
  1084. if srf in url_map:
  1085. video_url_list = [(srf, url_map[srf])]
  1086. break
  1087. else:
  1088. continue
  1089. break
  1090. if video_url_list is None:
  1091. raise ExtractorError(u'requested format not available')
  1092. return video_url_list
  1093. def _extract_from_m3u8(self, manifest_url, video_id):
  1094. url_map = {}
  1095. def _get_urls(_manifest):
  1096. lines = _manifest.split('\n')
  1097. urls = filter(lambda l: l and not l.startswith('#'),
  1098. lines)
  1099. return urls
  1100. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  1101. formats_urls = _get_urls(manifest)
  1102. for format_url in formats_urls:
  1103. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1104. url_map[itag] = format_url
  1105. return url_map
  1106. def _real_extract(self, url):
  1107. if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
  1108. 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 ).')
  1109. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1110. mobj = re.search(self._NEXT_URL_RE, url)
  1111. if mobj:
  1112. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  1113. video_id = self._extract_id(url)
  1114. # Get video webpage
  1115. self.report_video_webpage_download(video_id)
  1116. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  1117. request = compat_urllib_request.Request(url)
  1118. try:
  1119. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  1120. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1121. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  1122. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  1123. # Attempt to extract SWF player URL
  1124. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1125. if mobj is not None:
  1126. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1127. else:
  1128. player_url = None
  1129. # Get video info
  1130. self.report_video_info_webpage_download(video_id)
  1131. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1132. self.report_age_confirmation()
  1133. age_gate = True
  1134. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1135. # this can be viewed without login into Youtube
  1136. data = compat_urllib_parse.urlencode({'video_id': video_id,
  1137. 'el': 'embedded',
  1138. 'gl': 'US',
  1139. 'hl': 'en',
  1140. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1141. 'asv': 3,
  1142. 'sts':'1588',
  1143. })
  1144. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  1145. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1146. note=False,
  1147. errnote='unable to download video info webpage')
  1148. video_info = compat_parse_qs(video_info_webpage)
  1149. else:
  1150. age_gate = False
  1151. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1152. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1153. % (video_id, el_type))
  1154. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1155. note=False,
  1156. errnote='unable to download video info webpage')
  1157. video_info = compat_parse_qs(video_info_webpage)
  1158. if 'token' in video_info:
  1159. break
  1160. if 'token' not in video_info:
  1161. if 'reason' in video_info:
  1162. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  1163. else:
  1164. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  1165. # Check for "rental" videos
  1166. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1167. raise ExtractorError(u'"rental" videos not supported')
  1168. # Start extracting information
  1169. self.report_information_extraction(video_id)
  1170. # uploader
  1171. if 'author' not in video_info:
  1172. raise ExtractorError(u'Unable to extract uploader name')
  1173. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1174. # uploader_id
  1175. video_uploader_id = None
  1176. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1177. if mobj is not None:
  1178. video_uploader_id = mobj.group(1)
  1179. else:
  1180. self._downloader.report_warning(u'unable to extract uploader nickname')
  1181. # title
  1182. if 'title' not in video_info:
  1183. raise ExtractorError(u'Unable to extract video title')
  1184. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  1185. # thumbnail image
  1186. # We try first to get a high quality image:
  1187. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1188. video_webpage, re.DOTALL)
  1189. if m_thumb is not None:
  1190. video_thumbnail = m_thumb.group(1)
  1191. elif 'thumbnail_url' not in video_info:
  1192. self._downloader.report_warning(u'unable to extract video thumbnail')
  1193. video_thumbnail = ''
  1194. else: # don't panic if we can't find it
  1195. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1196. # upload date
  1197. upload_date = None
  1198. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1199. if mobj is not None:
  1200. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1201. upload_date = unified_strdate(upload_date)
  1202. # description
  1203. video_description = get_element_by_id("eow-description", video_webpage)
  1204. if video_description:
  1205. video_description = clean_html(video_description)
  1206. else:
  1207. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1208. if fd_mobj:
  1209. video_description = unescapeHTML(fd_mobj.group(1))
  1210. else:
  1211. video_description = u''
  1212. # subtitles
  1213. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1214. if self._downloader.params.get('listsubtitles', False):
  1215. self._list_available_subtitles(video_id, video_webpage)
  1216. return
  1217. if 'length_seconds' not in video_info:
  1218. self._downloader.report_warning(u'unable to extract video duration')
  1219. video_duration = ''
  1220. else:
  1221. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  1222. # Decide which formats to download
  1223. try:
  1224. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  1225. if not mobj:
  1226. raise ValueError('Could not find vevo ID')
  1227. info = json.loads(mobj.group(1))
  1228. args = info['args']
  1229. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1230. # this signatures are encrypted
  1231. m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
  1232. if m_s is not None:
  1233. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1234. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1235. m_s = re.search(r'[&,]s=', args.get('adaptive_fmts', u''))
  1236. if m_s is not None:
  1237. if 'url_encoded_fmt_stream_map' in video_info:
  1238. video_info['url_encoded_fmt_stream_map'][0] += ',' + args['adaptive_fmts']
  1239. else:
  1240. video_info['url_encoded_fmt_stream_map'] = [args['adaptive_fmts']]
  1241. elif 'adaptive_fmts' in video_info:
  1242. if 'url_encoded_fmt_stream_map' in video_info:
  1243. video_info['url_encoded_fmt_stream_map'][0] += ',' + video_info['adaptive_fmts'][0]
  1244. else:
  1245. video_info['url_encoded_fmt_stream_map'] = video_info['adaptive_fmts']
  1246. except ValueError:
  1247. pass
  1248. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1249. self.report_rtmp_download()
  1250. video_url_list = [(None, video_info['conn'][0])]
  1251. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  1252. if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
  1253. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1254. url_map = {}
  1255. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  1256. url_data = compat_parse_qs(url_data_str)
  1257. if 'itag' in url_data and 'url' in url_data:
  1258. url = url_data['url'][0]
  1259. if 'sig' in url_data:
  1260. url += '&signature=' + url_data['sig'][0]
  1261. elif 's' in url_data:
  1262. encrypted_sig = url_data['s'][0]
  1263. if self._downloader.params.get('verbose'):
  1264. if age_gate:
  1265. player_version = self._search_regex(
  1266. r'-(.+)\.swf$',
  1267. player_url if player_url else None,
  1268. 'flash player', fatal=False)
  1269. player_desc = 'flash player %s' % player_version
  1270. else:
  1271. player_version = self._search_regex(
  1272. r'html5player-(.+?)\.js', video_webpage,
  1273. 'html5 player', fatal=False)
  1274. player_desc = u'html5 player %s' % player_version
  1275. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1276. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1277. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1278. if not age_gate:
  1279. jsplayer_url_json = self._search_regex(
  1280. r'"assets":.+?"js":\s*("[^"]+")',
  1281. video_webpage, u'JS player URL')
  1282. player_url = json.loads(jsplayer_url_json)
  1283. signature = self._decrypt_signature(
  1284. encrypted_sig, video_id, player_url, age_gate)
  1285. url += '&signature=' + signature
  1286. if 'ratebypass' not in url:
  1287. url += '&ratebypass=yes'
  1288. url_map[url_data['itag'][0]] = url
  1289. video_url_list = self._get_video_url_list(url_map)
  1290. if not video_url_list:
  1291. return
  1292. elif video_info.get('hlsvp'):
  1293. manifest_url = video_info['hlsvp'][0]
  1294. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1295. video_url_list = self._get_video_url_list(url_map)
  1296. if not video_url_list:
  1297. return
  1298. else:
  1299. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  1300. results = []
  1301. for format_param, video_real_url in video_url_list:
  1302. # Extension
  1303. video_extension = self._video_extensions.get(format_param, 'flv')
  1304. video_format = '{0} - {1}{2}'.format(format_param if format_param else video_extension,
  1305. self._video_dimensions.get(format_param, '???'),
  1306. ' ('+self._special_itags[format_param]+')' if format_param in self._special_itags else '')
  1307. results.append({
  1308. 'id': video_id,
  1309. 'url': video_real_url,
  1310. 'uploader': video_uploader,
  1311. 'uploader_id': video_uploader_id,
  1312. 'upload_date': upload_date,
  1313. 'title': video_title,
  1314. 'ext': video_extension,
  1315. 'format': video_format,
  1316. 'thumbnail': video_thumbnail,
  1317. 'description': video_description,
  1318. 'player_url': player_url,
  1319. 'subtitles': video_subtitles,
  1320. 'duration': video_duration
  1321. })
  1322. return results
  1323. class YoutubePlaylistIE(InfoExtractor):
  1324. IE_DESC = u'YouTube.com playlists'
  1325. _VALID_URL = r"""(?:
  1326. (?:https?://)?
  1327. (?:\w+\.)?
  1328. youtube\.com/
  1329. (?:
  1330. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1331. \? (?:.*?&)*? (?:p|a|list)=
  1332. | p/
  1333. )
  1334. ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
  1335. .*
  1336. |
  1337. ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
  1338. )"""
  1339. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  1340. _MAX_RESULTS = 50
  1341. IE_NAME = u'youtube:playlist'
  1342. @classmethod
  1343. def suitable(cls, url):
  1344. """Receives a URL and returns True if suitable for this IE."""
  1345. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1346. def _real_extract(self, url):
  1347. # Extract playlist id
  1348. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1349. if mobj is None:
  1350. raise ExtractorError(u'Invalid URL: %s' % url)
  1351. # Download playlist videos from API
  1352. playlist_id = mobj.group(1) or mobj.group(2)
  1353. videos = []
  1354. for page_num in itertools.count(1):
  1355. start_index = self._MAX_RESULTS * (page_num - 1) + 1
  1356. if start_index >= 1000:
  1357. self._downloader.report_warning(u'Max number of results reached')
  1358. break
  1359. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, start_index)
  1360. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1361. try:
  1362. response = json.loads(page)
  1363. except ValueError as err:
  1364. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1365. if 'feed' not in response:
  1366. raise ExtractorError(u'Got a malformed response from YouTube API')
  1367. playlist_title = response['feed']['title']['$t']
  1368. if 'entry' not in response['feed']:
  1369. # Number of videos is a multiple of self._MAX_RESULTS
  1370. break
  1371. for entry in response['feed']['entry']:
  1372. index = entry['yt$position']['$t']
  1373. if 'media$group' in entry and 'yt$videoid' in entry['media$group']:
  1374. videos.append((
  1375. index,
  1376. 'https://www.youtube.com/watch?v=' + entry['media$group']['yt$videoid']['$t']
  1377. ))
  1378. videos = [v[1] for v in sorted(videos)]
  1379. url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
  1380. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  1381. class YoutubeChannelIE(InfoExtractor):
  1382. IE_DESC = u'YouTube.com channels'
  1383. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1384. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1385. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1386. _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'
  1387. IE_NAME = u'youtube:channel'
  1388. def extract_videos_from_page(self, page):
  1389. ids_in_page = []
  1390. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1391. if mobj.group(1) not in ids_in_page:
  1392. ids_in_page.append(mobj.group(1))
  1393. return ids_in_page
  1394. def _real_extract(self, url):
  1395. # Extract channel id
  1396. mobj = re.match(self._VALID_URL, url)
  1397. if mobj is None:
  1398. raise ExtractorError(u'Invalid URL: %s' % url)
  1399. # Download channel page
  1400. channel_id = mobj.group(1)
  1401. video_ids = []
  1402. pagenum = 1
  1403. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1404. page = self._download_webpage(url, channel_id,
  1405. u'Downloading page #%s' % pagenum)
  1406. # Extract video identifiers
  1407. ids_in_page = self.extract_videos_from_page(page)
  1408. video_ids.extend(ids_in_page)
  1409. # Download any subsequent channel pages using the json-based channel_ajax query
  1410. if self._MORE_PAGES_INDICATOR in page:
  1411. for pagenum in itertools.count(1):
  1412. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1413. page = self._download_webpage(url, channel_id,
  1414. u'Downloading page #%s' % pagenum)
  1415. page = json.loads(page)
  1416. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1417. video_ids.extend(ids_in_page)
  1418. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1419. break
  1420. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1421. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  1422. url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
  1423. return [self.playlist_result(url_entries, channel_id)]
  1424. class YoutubeUserIE(InfoExtractor):
  1425. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1426. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?)|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1427. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1428. _GDATA_PAGE_SIZE = 50
  1429. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1430. IE_NAME = u'youtube:user'
  1431. @classmethod
  1432. def suitable(cls, url):
  1433. # Don't return True if the url can be extracted with other youtube
  1434. # extractor, the regex would is too permissive and it would match.
  1435. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1436. if any(ie.suitable(url) for ie in other_ies): return False
  1437. else: return super(YoutubeUserIE, cls).suitable(url)
  1438. def _real_extract(self, url):
  1439. # Extract username
  1440. mobj = re.match(self._VALID_URL, url)
  1441. if mobj is None:
  1442. raise ExtractorError(u'Invalid URL: %s' % url)
  1443. username = mobj.group(1)
  1444. # Download video ids using YouTube Data API. Result size per
  1445. # query is limited (currently to 50 videos) so we need to query
  1446. # page by page until there are no video ids - it means we got
  1447. # all of them.
  1448. video_ids = []
  1449. for pagenum in itertools.count(0):
  1450. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1451. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1452. page = self._download_webpage(gdata_url, username,
  1453. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  1454. try:
  1455. response = json.loads(page)
  1456. except ValueError as err:
  1457. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1458. if 'entry' not in response['feed']:
  1459. # Number of videos is a multiple of self._MAX_RESULTS
  1460. break
  1461. # Extract video identifiers
  1462. ids_in_page = []
  1463. for entry in response['feed']['entry']:
  1464. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  1465. video_ids.extend(ids_in_page)
  1466. # A little optimization - if current page is not
  1467. # "full", ie. does not contain PAGE_SIZE video ids then
  1468. # we can assume that this page is the last one - there
  1469. # are no more ids on further pages - no need to query
  1470. # again.
  1471. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1472. break
  1473. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  1474. url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
  1475. return [self.playlist_result(url_results, playlist_title = username)]
  1476. class YoutubeSearchIE(SearchInfoExtractor):
  1477. IE_DESC = u'YouTube.com searches'
  1478. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1479. _MAX_RESULTS = 1000
  1480. IE_NAME = u'youtube:search'
  1481. _SEARCH_KEY = 'ytsearch'
  1482. def report_download_page(self, query, pagenum):
  1483. """Report attempt to download search page with given number."""
  1484. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1485. def _get_n_results(self, query, n):
  1486. """Get a specified number of results for a query"""
  1487. video_ids = []
  1488. pagenum = 0
  1489. limit = n
  1490. while (50 * pagenum) < limit:
  1491. self.report_download_page(query, pagenum+1)
  1492. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1493. request = compat_urllib_request.Request(result_url)
  1494. try:
  1495. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1496. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1497. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  1498. api_response = json.loads(data)['data']
  1499. if not 'items' in api_response:
  1500. raise ExtractorError(u'[youtube] No video results')
  1501. new_ids = list(video['id'] for video in api_response['items'])
  1502. video_ids += new_ids
  1503. limit = min(n, api_response['totalItems'])
  1504. pagenum += 1
  1505. if len(video_ids) > n:
  1506. video_ids = video_ids[:n]
  1507. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  1508. return self.playlist_result(videos, query)
  1509. class YoutubeShowIE(InfoExtractor):
  1510. IE_DESC = u'YouTube.com (multi-season) shows'
  1511. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1512. IE_NAME = u'youtube:show'
  1513. def _real_extract(self, url):
  1514. mobj = re.match(self._VALID_URL, url)
  1515. show_name = mobj.group(1)
  1516. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1517. # There's one playlist for each season of the show
  1518. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1519. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1520. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1521. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1522. """
  1523. Base class for extractors that fetch info from
  1524. http://www.youtube.com/feed_ajax
  1525. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1526. """
  1527. _LOGIN_REQUIRED = True
  1528. _PAGING_STEP = 30
  1529. # use action_load_personal_feed instead of action_load_system_feed
  1530. _PERSONAL_FEED = False
  1531. @property
  1532. def _FEED_TEMPLATE(self):
  1533. action = 'action_load_system_feed'
  1534. if self._PERSONAL_FEED:
  1535. action = 'action_load_personal_feed'
  1536. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1537. @property
  1538. def IE_NAME(self):
  1539. return u'youtube:%s' % self._FEED_NAME
  1540. def _real_initialize(self):
  1541. self._login()
  1542. def _real_extract(self, url):
  1543. feed_entries = []
  1544. # The step argument is available only in 2.7 or higher
  1545. for i in itertools.count(0):
  1546. paging = i*self._PAGING_STEP
  1547. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  1548. u'%s feed' % self._FEED_NAME,
  1549. u'Downloading page %s' % i)
  1550. info = json.loads(info)
  1551. feed_html = info['feed_html']
  1552. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1553. ids = orderedSet(m.group(1) for m in m_ids)
  1554. feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
  1555. if info['paging'] is None:
  1556. break
  1557. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1558. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1559. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1560. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1561. _FEED_NAME = 'subscriptions'
  1562. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1563. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1564. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1565. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1566. _FEED_NAME = 'recommended'
  1567. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1568. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1569. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1570. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1571. _FEED_NAME = 'watch_later'
  1572. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1573. _PAGING_STEP = 100
  1574. _PERSONAL_FEED = True
  1575. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1576. IE_NAME = u'youtube:favorites'
  1577. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1578. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1579. _LOGIN_REQUIRED = True
  1580. def _real_extract(self, url):
  1581. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1582. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1583. return self.url_result(playlist_id, 'YoutubePlaylist')