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.

1857 lines
77 KiB

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