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.

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