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.

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