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.

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