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.

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