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.

1820 lines
78 KiB

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