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.

1763 lines
76 KiB

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