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.

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