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.

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