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.

1815 lines
75 KiB

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