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.

1839 lines
80 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 not None:
  798. if player_url.startswith(u'//'):
  799. player_url = u'https:' + player_url
  800. try:
  801. player_id = (player_url, len(s))
  802. if player_id not in self._player_cache:
  803. func = self._extract_signature_function(
  804. video_id, player_url, len(s)
  805. )
  806. self._player_cache[player_id] = func
  807. func = self._player_cache[player_id]
  808. if self._downloader.params.get('youtube_print_sig_code'):
  809. self._print_sig_code(func, len(s))
  810. return func(s)
  811. except Exception:
  812. tb = traceback.format_exc()
  813. self._downloader.report_warning(
  814. u'Automatic signature extraction failed: ' + tb)
  815. self._downloader.report_warning(
  816. u'Warning: Falling back to static signature algorithm')
  817. return self._static_decrypt_signature(
  818. s, video_id, player_url, age_gate)
  819. def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
  820. if age_gate:
  821. # The videos with age protection use another player, so the
  822. # algorithms can be different.
  823. if len(s) == 86:
  824. return s[2:63] + s[82] + s[64:82] + s[63]
  825. if len(s) == 93:
  826. return s[86:29:-1] + s[88] + s[28:5:-1]
  827. elif len(s) == 92:
  828. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  829. elif len(s) == 91:
  830. return s[84:27:-1] + s[86] + s[26:5:-1]
  831. elif len(s) == 90:
  832. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  833. elif len(s) == 89:
  834. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  835. elif len(s) == 88:
  836. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  837. elif len(s) == 87:
  838. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  839. elif len(s) == 86:
  840. return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
  841. elif len(s) == 85:
  842. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  843. elif len(s) == 84:
  844. return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
  845. elif len(s) == 83:
  846. return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
  847. elif len(s) == 82:
  848. return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
  849. elif len(s) == 81:
  850. 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]
  851. elif len(s) == 80:
  852. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  853. elif len(s) == 79:
  854. 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]
  855. else:
  856. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  857. def _get_available_subtitles(self, video_id, webpage):
  858. try:
  859. sub_list = self._download_webpage(
  860. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  861. video_id, note=False)
  862. except ExtractorError as err:
  863. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  864. return {}
  865. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  866. sub_lang_list = {}
  867. for l in lang_list:
  868. lang = l[1]
  869. params = compat_urllib_parse.urlencode({
  870. 'lang': lang,
  871. 'v': video_id,
  872. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  873. 'name': unescapeHTML(l[0]).encode('utf-8'),
  874. })
  875. url = u'https://www.youtube.com/api/timedtext?' + params
  876. sub_lang_list[lang] = url
  877. if not sub_lang_list:
  878. self._downloader.report_warning(u'video doesn\'t have subtitles')
  879. return {}
  880. return sub_lang_list
  881. def _get_available_automatic_caption(self, video_id, webpage):
  882. """We need the webpage for getting the captions url, pass it as an
  883. argument to speed up the process."""
  884. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  885. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  886. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  887. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  888. if mobj is None:
  889. self._downloader.report_warning(err_msg)
  890. return {}
  891. player_config = json.loads(mobj.group(1))
  892. try:
  893. args = player_config[u'args']
  894. caption_url = args[u'ttsurl']
  895. timestamp = args[u'timestamp']
  896. # We get the available subtitles
  897. list_params = compat_urllib_parse.urlencode({
  898. 'type': 'list',
  899. 'tlangs': 1,
  900. 'asrs': 1,
  901. })
  902. list_url = caption_url + '&' + list_params
  903. caption_list = self._download_xml(list_url, video_id)
  904. original_lang_node = caption_list.find('track')
  905. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  906. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  907. return {}
  908. original_lang = original_lang_node.attrib['lang_code']
  909. sub_lang_list = {}
  910. for lang_node in caption_list.findall('target'):
  911. sub_lang = lang_node.attrib['lang_code']
  912. params = compat_urllib_parse.urlencode({
  913. 'lang': original_lang,
  914. 'tlang': sub_lang,
  915. 'fmt': sub_format,
  916. 'ts': timestamp,
  917. 'kind': 'asr',
  918. })
  919. sub_lang_list[sub_lang] = caption_url + '&' + params
  920. return sub_lang_list
  921. # An extractor error can be raise by the download process if there are
  922. # no automatic captions but there are subtitles
  923. except (KeyError, ExtractorError):
  924. self._downloader.report_warning(err_msg)
  925. return {}
  926. @classmethod
  927. def extract_id(cls, url):
  928. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  929. if mobj is None:
  930. raise ExtractorError(u'Invalid URL: %s' % url)
  931. video_id = mobj.group(2)
  932. return video_id
  933. def _extract_from_m3u8(self, manifest_url, video_id):
  934. url_map = {}
  935. def _get_urls(_manifest):
  936. lines = _manifest.split('\n')
  937. urls = filter(lambda l: l and not l.startswith('#'),
  938. lines)
  939. return urls
  940. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  941. formats_urls = _get_urls(manifest)
  942. for format_url in formats_urls:
  943. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  944. url_map[itag] = format_url
  945. return url_map
  946. def _extract_annotations(self, video_id):
  947. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  948. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  949. def _real_extract(self, url):
  950. proto = (
  951. u'http' if self._downloader.params.get('prefer_insecure', False)
  952. else u'https')
  953. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  954. mobj = re.search(self._NEXT_URL_RE, url)
  955. if mobj:
  956. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  957. video_id = self.extract_id(url)
  958. # Get video webpage
  959. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  960. video_webpage = self._download_webpage(url, video_id)
  961. # Attempt to extract SWF player URL
  962. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  963. if mobj is not None:
  964. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  965. else:
  966. player_url = None
  967. # Get video info
  968. self.report_video_info_webpage_download(video_id)
  969. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  970. self.report_age_confirmation()
  971. age_gate = True
  972. # We simulate the access to the video from www.youtube.com/v/{video_id}
  973. # this can be viewed without login into Youtube
  974. data = compat_urllib_parse.urlencode({'video_id': video_id,
  975. 'el': 'player_embedded',
  976. 'gl': 'US',
  977. 'hl': 'en',
  978. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  979. 'asv': 3,
  980. 'sts':'1588',
  981. })
  982. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  983. video_info_webpage = self._download_webpage(video_info_url, video_id,
  984. note=False,
  985. errnote='unable to download video info webpage')
  986. video_info = compat_parse_qs(video_info_webpage)
  987. else:
  988. age_gate = False
  989. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  990. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  991. % (video_id, el_type))
  992. video_info_webpage = self._download_webpage(video_info_url, video_id,
  993. note=False,
  994. errnote='unable to download video info webpage')
  995. video_info = compat_parse_qs(video_info_webpage)
  996. if 'token' in video_info:
  997. break
  998. if 'token' not in video_info:
  999. if 'reason' in video_info:
  1000. raise ExtractorError(
  1001. u'YouTube said: %s' % video_info['reason'][0],
  1002. expected=True, video_id=video_id)
  1003. else:
  1004. raise ExtractorError(
  1005. u'"token" parameter not in video info for unknown reason',
  1006. video_id=video_id)
  1007. if 'view_count' in video_info:
  1008. view_count = int(video_info['view_count'][0])
  1009. else:
  1010. view_count = None
  1011. # Check for "rental" videos
  1012. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1013. raise ExtractorError(u'"rental" videos not supported')
  1014. # Start extracting information
  1015. self.report_information_extraction(video_id)
  1016. # uploader
  1017. if 'author' not in video_info:
  1018. raise ExtractorError(u'Unable to extract uploader name')
  1019. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1020. # uploader_id
  1021. video_uploader_id = None
  1022. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1023. if mobj is not None:
  1024. video_uploader_id = mobj.group(1)
  1025. else:
  1026. self._downloader.report_warning(u'unable to extract uploader nickname')
  1027. # title
  1028. if 'title' in video_info:
  1029. video_title = video_info['title'][0]
  1030. else:
  1031. self._downloader.report_warning(u'Unable to extract video title')
  1032. video_title = u'_'
  1033. # thumbnail image
  1034. # We try first to get a high quality image:
  1035. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1036. video_webpage, re.DOTALL)
  1037. if m_thumb is not None:
  1038. video_thumbnail = m_thumb.group(1)
  1039. elif 'thumbnail_url' not in video_info:
  1040. self._downloader.report_warning(u'unable to extract video thumbnail')
  1041. video_thumbnail = None
  1042. else: # don't panic if we can't find it
  1043. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1044. # upload date
  1045. upload_date = None
  1046. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  1047. if mobj is None:
  1048. mobj = re.search(
  1049. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  1050. video_webpage)
  1051. if mobj is not None:
  1052. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1053. upload_date = unified_strdate(upload_date)
  1054. m_cat_container = get_element_by_id("eow-category", video_webpage)
  1055. if m_cat_container:
  1056. category = self._html_search_regex(
  1057. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1058. default=None)
  1059. video_categories = None if category is None else [category]
  1060. else:
  1061. video_categories = None
  1062. # description
  1063. video_description = get_element_by_id("eow-description", video_webpage)
  1064. if video_description:
  1065. video_description = re.sub(r'''(?x)
  1066. <a\s+
  1067. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1068. title="([^"]+)"\s+
  1069. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1070. class="yt-uix-redirect-link"\s*>
  1071. [^<]+
  1072. </a>
  1073. ''', r'\1', video_description)
  1074. video_description = clean_html(video_description)
  1075. else:
  1076. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1077. if fd_mobj:
  1078. video_description = unescapeHTML(fd_mobj.group(1))
  1079. else:
  1080. video_description = u''
  1081. def _extract_count(klass):
  1082. count = self._search_regex(
  1083. r'class="%s">([\d,]+)</span>' % re.escape(klass),
  1084. video_webpage, klass, default=None)
  1085. if count is not None:
  1086. return int(count.replace(',', ''))
  1087. return None
  1088. like_count = _extract_count(u'likes-count')
  1089. dislike_count = _extract_count(u'dislikes-count')
  1090. # subtitles
  1091. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1092. if self._downloader.params.get('listsubtitles', False):
  1093. self._list_available_subtitles(video_id, video_webpage)
  1094. return
  1095. if 'length_seconds' not in video_info:
  1096. self._downloader.report_warning(u'unable to extract video duration')
  1097. video_duration = None
  1098. else:
  1099. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  1100. # annotations
  1101. video_annotations = None
  1102. if self._downloader.params.get('writeannotations', False):
  1103. video_annotations = self._extract_annotations(video_id)
  1104. # Decide which formats to download
  1105. try:
  1106. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  1107. if not mobj:
  1108. raise ValueError('Could not find vevo ID')
  1109. json_code = uppercase_escape(mobj.group(1))
  1110. ytplayer_config = json.loads(json_code)
  1111. args = ytplayer_config['args']
  1112. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1113. # this signatures are encrypted
  1114. if 'url_encoded_fmt_stream_map' not in args:
  1115. raise ValueError(u'No stream_map present') # caught below
  1116. re_signature = re.compile(r'[&,]s=')
  1117. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  1118. if m_s is not None:
  1119. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1120. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1121. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  1122. if m_s is not None:
  1123. if 'adaptive_fmts' in video_info:
  1124. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  1125. else:
  1126. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  1127. except ValueError:
  1128. pass
  1129. def _map_to_format_list(urlmap):
  1130. formats = []
  1131. for itag, video_real_url in urlmap.items():
  1132. dct = {
  1133. 'format_id': itag,
  1134. 'url': video_real_url,
  1135. 'player_url': player_url,
  1136. }
  1137. if itag in self._formats:
  1138. dct.update(self._formats[itag])
  1139. formats.append(dct)
  1140. return formats
  1141. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1142. self.report_rtmp_download()
  1143. formats = [{
  1144. 'format_id': '_rtmp',
  1145. 'protocol': 'rtmp',
  1146. 'url': video_info['conn'][0],
  1147. 'player_url': player_url,
  1148. }]
  1149. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  1150. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  1151. if 'rtmpe%3Dyes' in encoded_url_map:
  1152. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1153. url_map = {}
  1154. for url_data_str in encoded_url_map.split(','):
  1155. url_data = compat_parse_qs(url_data_str)
  1156. if 'itag' in url_data and 'url' in url_data:
  1157. url = url_data['url'][0]
  1158. if 'sig' in url_data:
  1159. url += '&signature=' + url_data['sig'][0]
  1160. elif 's' in url_data:
  1161. encrypted_sig = url_data['s'][0]
  1162. if self._downloader.params.get('verbose'):
  1163. if age_gate:
  1164. if player_url is None:
  1165. player_version = 'unknown'
  1166. else:
  1167. player_version = self._search_regex(
  1168. r'-(.+)\.swf$', player_url,
  1169. u'flash player', fatal=False)
  1170. player_desc = 'flash player %s' % player_version
  1171. else:
  1172. player_version = self._search_regex(
  1173. r'html5player-(.+?)\.js', video_webpage,
  1174. 'html5 player', fatal=False)
  1175. player_desc = u'html5 player %s' % player_version
  1176. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1177. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1178. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1179. if not age_gate:
  1180. jsplayer_url_json = self._search_regex(
  1181. r'"assets":.+?"js":\s*("[^"]+")',
  1182. video_webpage, u'JS player URL')
  1183. player_url = json.loads(jsplayer_url_json)
  1184. signature = self._decrypt_signature(
  1185. encrypted_sig, video_id, player_url, age_gate)
  1186. url += '&signature=' + signature
  1187. if 'ratebypass' not in url:
  1188. url += '&ratebypass=yes'
  1189. url_map[url_data['itag'][0]] = url
  1190. formats = _map_to_format_list(url_map)
  1191. elif video_info.get('hlsvp'):
  1192. manifest_url = video_info['hlsvp'][0]
  1193. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1194. formats = _map_to_format_list(url_map)
  1195. else:
  1196. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1197. # Look for the DASH manifest
  1198. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  1199. try:
  1200. # The DASH manifest used needs to be the one from the original video_webpage.
  1201. # The one found in get_video_info seems to be using different signatures.
  1202. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  1203. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  1204. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  1205. if age_gate:
  1206. dash_manifest_url = video_info.get('dashmpd')[0]
  1207. else:
  1208. dash_manifest_url = ytplayer_config['args']['dashmpd']
  1209. def decrypt_sig(mobj):
  1210. s = mobj.group(1)
  1211. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  1212. return '/signature/%s' % dec_s
  1213. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  1214. dash_doc = self._download_xml(
  1215. dash_manifest_url, video_id,
  1216. note=u'Downloading DASH manifest',
  1217. errnote=u'Could not download DASH manifest')
  1218. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  1219. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  1220. if url_el is None:
  1221. continue
  1222. format_id = r.attrib['id']
  1223. video_url = url_el.text
  1224. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  1225. f = {
  1226. 'format_id': format_id,
  1227. 'url': video_url,
  1228. 'width': int_or_none(r.attrib.get('width')),
  1229. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  1230. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  1231. 'filesize': filesize,
  1232. }
  1233. try:
  1234. existing_format = next(
  1235. fo for fo in formats
  1236. if fo['format_id'] == format_id)
  1237. except StopIteration:
  1238. f.update(self._formats.get(format_id, {}))
  1239. formats.append(f)
  1240. else:
  1241. existing_format.update(f)
  1242. except (ExtractorError, KeyError) as e:
  1243. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  1244. self._sort_formats(formats)
  1245. return {
  1246. 'id': video_id,
  1247. 'uploader': video_uploader,
  1248. 'uploader_id': video_uploader_id,
  1249. 'upload_date': upload_date,
  1250. 'title': video_title,
  1251. 'thumbnail': video_thumbnail,
  1252. 'description': video_description,
  1253. 'categories': video_categories,
  1254. 'subtitles': video_subtitles,
  1255. 'duration': video_duration,
  1256. 'age_limit': 18 if age_gate else 0,
  1257. 'annotations': video_annotations,
  1258. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1259. 'view_count': view_count,
  1260. 'like_count': like_count,
  1261. 'dislike_count': dislike_count,
  1262. 'formats': formats,
  1263. }
  1264. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1265. IE_DESC = u'YouTube.com playlists'
  1266. _VALID_URL = r"""(?x)(?:
  1267. (?:https?://)?
  1268. (?:\w+\.)?
  1269. youtube\.com/
  1270. (?:
  1271. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1272. \? (?:.*?&)*? (?:p|a|list)=
  1273. | p/
  1274. )
  1275. (
  1276. (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  1277. # Top tracks, they can also include dots
  1278. |(?:MC)[\w\.]*
  1279. )
  1280. .*
  1281. |
  1282. ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  1283. )"""
  1284. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1285. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  1286. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1287. IE_NAME = u'youtube:playlist'
  1288. def _real_initialize(self):
  1289. self._login()
  1290. def _ids_to_results(self, ids):
  1291. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1292. for vid_id in ids]
  1293. def _extract_mix(self, playlist_id):
  1294. # The mixes are generated from a a single video
  1295. # the id of the playlist is just 'RD' + video_id
  1296. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1297. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  1298. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1299. title_span = (search_title('playlist-title') or
  1300. search_title('title long-title') or search_title('title'))
  1301. title = clean_html(title_span)
  1302. video_re = r'''(?x)data-video-username=".*?".*?
  1303. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id)
  1304. ids = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
  1305. url_results = self._ids_to_results(ids)
  1306. return self.playlist_result(url_results, playlist_id, title)
  1307. def _real_extract(self, url):
  1308. # Extract playlist id
  1309. mobj = re.match(self._VALID_URL, url)
  1310. if mobj is None:
  1311. raise ExtractorError(u'Invalid URL: %s' % url)
  1312. playlist_id = mobj.group(1) or mobj.group(2)
  1313. # Check if it's a video-specific URL
  1314. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1315. if 'v' in query_dict:
  1316. video_id = query_dict['v'][0]
  1317. if self._downloader.params.get('noplaylist'):
  1318. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  1319. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1320. else:
  1321. self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1322. if playlist_id.startswith('RD'):
  1323. # Mixes require a custom extraction process
  1324. return self._extract_mix(playlist_id)
  1325. if playlist_id.startswith('TL'):
  1326. raise ExtractorError(u'For downloading YouTube.com top lists, use '
  1327. u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  1328. url = self._TEMPLATE_URL % playlist_id
  1329. page = self._download_webpage(url, playlist_id)
  1330. more_widget_html = content_html = page
  1331. # Check if the playlist exists or is private
  1332. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  1333. raise ExtractorError(
  1334. u'The playlist doesn\'t exist or is private, use --username or '
  1335. '--netrc to access it.',
  1336. expected=True)
  1337. # Extract the video ids from the playlist pages
  1338. ids = []
  1339. for page_num in itertools.count(1):
  1340. matches = re.finditer(self._VIDEO_RE, content_html)
  1341. # We remove the duplicates and the link with index 0
  1342. # (it's not the first video of the playlist)
  1343. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1344. ids.extend(new_ids)
  1345. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1346. if not mobj:
  1347. break
  1348. more = self._download_json(
  1349. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  1350. 'Downloading page #%s' % page_num,
  1351. transform_source=uppercase_escape)
  1352. content_html = more['content_html']
  1353. more_widget_html = more['load_more_widget_html']
  1354. playlist_title = self._html_search_regex(
  1355. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  1356. page, u'title')
  1357. url_results = self._ids_to_results(ids)
  1358. return self.playlist_result(url_results, playlist_id, playlist_title)
  1359. class YoutubeTopListIE(YoutubePlaylistIE):
  1360. IE_NAME = u'youtube:toplist'
  1361. IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  1362. u' (Example: "yttoplist:music:Top Tracks")')
  1363. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  1364. def _real_extract(self, url):
  1365. mobj = re.match(self._VALID_URL, url)
  1366. channel = mobj.group('chann')
  1367. title = mobj.group('title')
  1368. query = compat_urllib_parse.urlencode({'title': title})
  1369. playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
  1370. channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
  1371. link = self._html_search_regex(playlist_re, channel_page, u'list')
  1372. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  1373. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  1374. ids = []
  1375. # sometimes the webpage doesn't contain the videos
  1376. # retry until we get them
  1377. for i in itertools.count(0):
  1378. msg = u'Downloading Youtube mix'
  1379. if i > 0:
  1380. msg += ', retry #%d' % i
  1381. webpage = self._download_webpage(url, title, msg)
  1382. ids = orderedSet(re.findall(video_re, webpage))
  1383. if ids:
  1384. break
  1385. url_results = self._ids_to_results(ids)
  1386. return self.playlist_result(url_results, playlist_title=title)
  1387. class YoutubeChannelIE(InfoExtractor):
  1388. IE_DESC = u'YouTube.com channels'
  1389. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1390. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1391. _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'
  1392. IE_NAME = u'youtube:channel'
  1393. def extract_videos_from_page(self, page):
  1394. ids_in_page = []
  1395. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1396. if mobj.group(1) not in ids_in_page:
  1397. ids_in_page.append(mobj.group(1))
  1398. return ids_in_page
  1399. def _real_extract(self, url):
  1400. # Extract channel id
  1401. mobj = re.match(self._VALID_URL, url)
  1402. if mobj is None:
  1403. raise ExtractorError(u'Invalid URL: %s' % url)
  1404. # Download channel page
  1405. channel_id = mobj.group(1)
  1406. video_ids = []
  1407. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1408. channel_page = self._download_webpage(url, channel_id)
  1409. autogenerated = re.search(r'''(?x)
  1410. class="[^"]*?(?:
  1411. channel-header-autogenerated-label|
  1412. yt-channel-title-autogenerated
  1413. )[^"]*"''', channel_page) is not None
  1414. if autogenerated:
  1415. # The videos are contained in a single page
  1416. # the ajax pages can't be used, they are empty
  1417. video_ids = self.extract_videos_from_page(channel_page)
  1418. else:
  1419. # Download all channel pages using the json-based channel_ajax query
  1420. for pagenum in itertools.count(1):
  1421. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1422. page = self._download_json(
  1423. url, channel_id, note=u'Downloading page #%s' % pagenum,
  1424. transform_source=uppercase_escape)
  1425. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1426. video_ids.extend(ids_in_page)
  1427. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1428. break
  1429. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1430. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1431. for video_id in video_ids]
  1432. return self.playlist_result(url_entries, channel_id)
  1433. class YoutubeUserIE(InfoExtractor):
  1434. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1435. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1436. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1437. _GDATA_PAGE_SIZE = 50
  1438. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1439. IE_NAME = u'youtube:user'
  1440. @classmethod
  1441. def suitable(cls, url):
  1442. # Don't return True if the url can be extracted with other youtube
  1443. # extractor, the regex would is too permissive and it would match.
  1444. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1445. if any(ie.suitable(url) for ie in other_ies): return False
  1446. else: return super(YoutubeUserIE, cls).suitable(url)
  1447. def _real_extract(self, url):
  1448. # Extract username
  1449. mobj = re.match(self._VALID_URL, url)
  1450. if mobj is None:
  1451. raise ExtractorError(u'Invalid URL: %s' % url)
  1452. username = mobj.group(1)
  1453. # Download video ids using YouTube Data API. Result size per
  1454. # query is limited (currently to 50 videos) so we need to query
  1455. # page by page until there are no video ids - it means we got
  1456. # all of them.
  1457. def download_page(pagenum):
  1458. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1459. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1460. page = self._download_webpage(
  1461. gdata_url, username,
  1462. u'Downloading video ids from %d to %d' % (
  1463. start_index, start_index + self._GDATA_PAGE_SIZE))
  1464. try:
  1465. response = json.loads(page)
  1466. except ValueError as err:
  1467. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1468. if 'entry' not in response['feed']:
  1469. return
  1470. # Extract video identifiers
  1471. entries = response['feed']['entry']
  1472. for entry in entries:
  1473. title = entry['title']['$t']
  1474. video_id = entry['id']['$t'].split('/')[-1]
  1475. yield {
  1476. '_type': 'url',
  1477. 'url': video_id,
  1478. 'ie_key': 'Youtube',
  1479. 'id': video_id,
  1480. 'title': title,
  1481. }
  1482. url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
  1483. return self.playlist_result(url_results, playlist_title=username)
  1484. class YoutubeSearchIE(SearchInfoExtractor):
  1485. IE_DESC = u'YouTube.com searches'
  1486. _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1487. _MAX_RESULTS = 1000
  1488. IE_NAME = u'youtube:search'
  1489. _SEARCH_KEY = 'ytsearch'
  1490. def _get_n_results(self, query, n):
  1491. """Get a specified number of results for a query"""
  1492. video_ids = []
  1493. pagenum = 0
  1494. limit = n
  1495. PAGE_SIZE = 50
  1496. while (PAGE_SIZE * pagenum) < limit:
  1497. result_url = self._API_URL % (
  1498. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1499. (PAGE_SIZE * pagenum) + 1)
  1500. data_json = self._download_webpage(
  1501. result_url, video_id=u'query "%s"' % query,
  1502. note=u'Downloading page %s' % (pagenum + 1),
  1503. errnote=u'Unable to download API page')
  1504. data = json.loads(data_json)
  1505. api_response = data['data']
  1506. if 'items' not in api_response:
  1507. raise ExtractorError(
  1508. u'[youtube] No video results', expected=True)
  1509. new_ids = list(video['id'] for video in api_response['items'])
  1510. video_ids += new_ids
  1511. limit = min(n, api_response['totalItems'])
  1512. pagenum += 1
  1513. if len(video_ids) > n:
  1514. video_ids = video_ids[:n]
  1515. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1516. for video_id in video_ids]
  1517. return self.playlist_result(videos, query)
  1518. class YoutubeSearchDateIE(YoutubeSearchIE):
  1519. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1520. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1521. _SEARCH_KEY = 'ytsearchdate'
  1522. IE_DESC = u'YouTube.com searches, newest videos first'
  1523. class YoutubeSearchURLIE(InfoExtractor):
  1524. IE_DESC = u'YouTube.com search URLs'
  1525. IE_NAME = u'youtube:search_url'
  1526. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1527. def _real_extract(self, url):
  1528. mobj = re.match(self._VALID_URL, url)
  1529. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1530. webpage = self._download_webpage(url, query)
  1531. result_code = self._search_regex(
  1532. r'(?s)<ol id="search-results"(.*?)</ol>', webpage, u'result HTML')
  1533. part_codes = re.findall(
  1534. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1535. entries = []
  1536. for part_code in part_codes:
  1537. part_title = self._html_search_regex(
  1538. r'(?s)title="([^"]+)"', part_code, 'item title', fatal=False)
  1539. part_url_snippet = self._html_search_regex(
  1540. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1541. part_url = compat_urlparse.urljoin(
  1542. 'https://www.youtube.com/', part_url_snippet)
  1543. entries.append({
  1544. '_type': 'url',
  1545. 'url': part_url,
  1546. 'title': part_title,
  1547. })
  1548. return {
  1549. '_type': 'playlist',
  1550. 'entries': entries,
  1551. 'title': query,
  1552. }
  1553. class YoutubeShowIE(InfoExtractor):
  1554. IE_DESC = u'YouTube.com (multi-season) shows'
  1555. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1556. IE_NAME = u'youtube:show'
  1557. def _real_extract(self, url):
  1558. mobj = re.match(self._VALID_URL, url)
  1559. show_name = mobj.group(1)
  1560. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1561. # There's one playlist for each season of the show
  1562. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1563. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1564. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1565. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1566. """
  1567. Base class for extractors that fetch info from
  1568. http://www.youtube.com/feed_ajax
  1569. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1570. """
  1571. _LOGIN_REQUIRED = True
  1572. # use action_load_personal_feed instead of action_load_system_feed
  1573. _PERSONAL_FEED = False
  1574. @property
  1575. def _FEED_TEMPLATE(self):
  1576. action = 'action_load_system_feed'
  1577. if self._PERSONAL_FEED:
  1578. action = 'action_load_personal_feed'
  1579. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1580. @property
  1581. def IE_NAME(self):
  1582. return u'youtube:%s' % self._FEED_NAME
  1583. def _real_initialize(self):
  1584. self._login()
  1585. def _real_extract(self, url):
  1586. feed_entries = []
  1587. paging = 0
  1588. for i in itertools.count(1):
  1589. info = self._download_json(self._FEED_TEMPLATE % paging,
  1590. u'%s feed' % self._FEED_NAME,
  1591. u'Downloading page %s' % i)
  1592. feed_html = info.get('feed_html') or info.get('content_html')
  1593. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1594. ids = orderedSet(m.group(1) for m in m_ids)
  1595. feed_entries.extend(
  1596. self.url_result(video_id, 'Youtube', video_id=video_id)
  1597. for video_id in ids)
  1598. mobj = re.search(
  1599. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1600. feed_html)
  1601. if mobj is None:
  1602. break
  1603. paging = mobj.group('paging')
  1604. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1605. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1606. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1607. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1608. _FEED_NAME = 'subscriptions'
  1609. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1610. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1611. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1612. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1613. _FEED_NAME = 'recommended'
  1614. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1615. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1616. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1617. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1618. _FEED_NAME = 'watch_later'
  1619. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1620. _PERSONAL_FEED = True
  1621. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1622. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1623. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1624. _FEED_NAME = 'history'
  1625. _PERSONAL_FEED = True
  1626. _PLAYLIST_TITLE = u'Youtube Watch History'
  1627. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1628. IE_NAME = u'youtube:favorites'
  1629. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1630. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1631. _LOGIN_REQUIRED = True
  1632. def _real_extract(self, url):
  1633. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1634. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1635. return self.url_result(playlist_id, 'YoutubePlaylist')
  1636. class YoutubeTruncatedURLIE(InfoExtractor):
  1637. IE_NAME = 'youtube:truncated_url'
  1638. IE_DESC = False # Do not list
  1639. _VALID_URL = r'''(?x)
  1640. (?:https?://)?[^/]+/watch\?(?:feature=[a-z_]+)?$|
  1641. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1642. '''
  1643. def _real_extract(self, url):
  1644. raise ExtractorError(
  1645. u'Did you forget to quote the URL? Remember that & is a meta '
  1646. u'character in most shells, so you want to put the URL in quotes, '
  1647. u'like youtube-dl '
  1648. u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1649. u' or simply youtube-dl BaW_jenozKc .',
  1650. expected=True)