You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1908 lines
79 KiB

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