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

12 years ago
  1. # coding: utf-8
  2. import collections
  3. import errno
  4. import io
  5. import itertools
  6. import json
  7. import os.path
  8. import re
  9. import 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. # Dash webm audio
  206. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 48, 'preference': -50},
  207. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  208. # RTMP (unnamed)
  209. '_rtmp': {'protocol': 'rtmp'},
  210. }
  211. IE_NAME = u'youtube'
  212. _TESTS = [
  213. {
  214. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  215. u"file": u"BaW_jenozKc.mp4",
  216. u"info_dict": {
  217. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  218. u"uploader": u"Philipp Hagemeister",
  219. u"uploader_id": u"phihag",
  220. u"upload_date": u"20121002",
  221. u"description": u"test chars: \"'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .",
  222. u"categories": [u'Science & Technology'],
  223. }
  224. },
  225. {
  226. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  227. u"file": u"UxxajLWwzqY.mp4",
  228. u"note": u"Test generic use_cipher_signature video (#897)",
  229. u"info_dict": {
  230. u"upload_date": u"20120506",
  231. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  232. u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
  233. u"uploader": u"Icona Pop",
  234. u"uploader_id": u"IconaPop"
  235. }
  236. },
  237. {
  238. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  239. u"file": u"07FYdnEawAQ.mp4",
  240. u"note": u"Test VEVO video with age protection (#956)",
  241. u"info_dict": {
  242. u"upload_date": u"20130703",
  243. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  244. u"description": u"md5:64249768eec3bc4276236606ea996373",
  245. u"uploader": u"justintimberlakeVEVO",
  246. u"uploader_id": u"justintimberlakeVEVO"
  247. }
  248. },
  249. {
  250. u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
  251. u"file": u"yZIXLfi8CZQ.mp4",
  252. u"note": u"Embed-only video (#1746)",
  253. u"info_dict": {
  254. u"upload_date": u"20120608",
  255. u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
  256. u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
  257. u"uploader": u"SET India",
  258. u"uploader_id": u"setindia"
  259. }
  260. },
  261. {
  262. u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
  263. u"file": u"a9LDPn-MO4I.m4a",
  264. u"note": u"256k DASH audio (format 141) via DASH manifest",
  265. u"info_dict": {
  266. u"upload_date": "20121002",
  267. u"uploader_id": "8KVIDEO",
  268. u"description": "No description available.",
  269. u"uploader": "8KVIDEO",
  270. u"title": "UHDTV TEST 8K VIDEO.mp4"
  271. },
  272. u"params": {
  273. u"youtube_include_dash_manifest": True,
  274. u"format": "141",
  275. },
  276. },
  277. # DASH manifest with encrypted signature
  278. {
  279. u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  280. u'info_dict': {
  281. u'id': u'IB3lcPjvWLA',
  282. u'ext': u'm4a',
  283. u'title': u'Afrojack - The Spark ft. Spree Wilson',
  284. u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8',
  285. u'uploader': u'AfrojackVEVO',
  286. u'uploader_id': u'AfrojackVEVO',
  287. u'upload_date': u'20131011',
  288. },
  289. u"params": {
  290. u'youtube_include_dash_manifest': True,
  291. u'format': '141',
  292. },
  293. },
  294. ]
  295. @classmethod
  296. def suitable(cls, url):
  297. """Receives a URL and returns True if suitable for this IE."""
  298. if YoutubePlaylistIE.suitable(url): return False
  299. return re.match(cls._VALID_URL, url) is not None
  300. def __init__(self, *args, **kwargs):
  301. super(YoutubeIE, self).__init__(*args, **kwargs)
  302. self._player_cache = {}
  303. def report_video_info_webpage_download(self, video_id):
  304. """Report attempt to download video info webpage."""
  305. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  306. def report_information_extraction(self, video_id):
  307. """Report attempt to extract video information."""
  308. self.to_screen(u'%s: Extracting video information' % video_id)
  309. def report_unavailable_format(self, video_id, format):
  310. """Report extracted video URL."""
  311. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  312. def report_rtmp_download(self):
  313. """Indicate the download will use the RTMP protocol."""
  314. self.to_screen(u'RTMP download detected')
  315. def _extract_signature_function(self, video_id, player_url, slen):
  316. id_m = re.match(r'.*-(?P<id>[a-zA-Z0-9_-]+)\.(?P<ext>[a-z]+)$',
  317. player_url)
  318. player_type = id_m.group('ext')
  319. player_id = id_m.group('id')
  320. # Read from filesystem cache
  321. func_id = '%s_%s_%d' % (player_type, player_id, slen)
  322. assert os.path.basename(func_id) == func_id
  323. cache_dir = get_cachedir(self._downloader.params)
  324. cache_enabled = cache_dir is not None
  325. if cache_enabled:
  326. cache_fn = os.path.join(os.path.expanduser(cache_dir),
  327. u'youtube-sigfuncs',
  328. func_id + '.json')
  329. try:
  330. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  331. cache_spec = json.load(cachef)
  332. return lambda s: u''.join(s[i] for i in cache_spec)
  333. except IOError:
  334. pass # No cache available
  335. if player_type == 'js':
  336. code = self._download_webpage(
  337. player_url, video_id,
  338. note=u'Downloading %s player %s' % (player_type, player_id),
  339. errnote=u'Download of %s failed' % player_url)
  340. res = self._parse_sig_js(code)
  341. elif player_type == 'swf':
  342. urlh = self._request_webpage(
  343. player_url, video_id,
  344. note=u'Downloading %s player %s' % (player_type, player_id),
  345. errnote=u'Download of %s failed' % player_url)
  346. code = urlh.read()
  347. res = self._parse_sig_swf(code)
  348. else:
  349. assert False, 'Invalid player type %r' % player_type
  350. if cache_enabled:
  351. try:
  352. test_string = u''.join(map(compat_chr, range(slen)))
  353. cache_res = res(test_string)
  354. cache_spec = [ord(c) for c in cache_res]
  355. try:
  356. os.makedirs(os.path.dirname(cache_fn))
  357. except OSError as ose:
  358. if ose.errno != errno.EEXIST:
  359. raise
  360. write_json_file(cache_spec, cache_fn)
  361. except Exception:
  362. tb = traceback.format_exc()
  363. self._downloader.report_warning(
  364. u'Writing cache to %r failed: %s' % (cache_fn, tb))
  365. return res
  366. def _print_sig_code(self, func, slen):
  367. def gen_sig_code(idxs):
  368. def _genslice(start, end, step):
  369. starts = u'' if start == 0 else str(start)
  370. ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
  371. steps = u'' if step == 1 else (u':%d' % step)
  372. return u's[%s%s%s]' % (starts, ends, steps)
  373. step = None
  374. start = '(Never used)' # Quelch pyflakes warnings - start will be
  375. # set as soon as step is set
  376. for i, prev in zip(idxs[1:], idxs[:-1]):
  377. if step is not None:
  378. if i - prev == step:
  379. continue
  380. yield _genslice(start, prev, step)
  381. step = None
  382. continue
  383. if i - prev in [-1, 1]:
  384. step = i - prev
  385. start = prev
  386. continue
  387. else:
  388. yield u's[%d]' % prev
  389. if step is None:
  390. yield u's[%d]' % i
  391. else:
  392. yield _genslice(start, i, step)
  393. test_string = u''.join(map(compat_chr, range(slen)))
  394. cache_res = func(test_string)
  395. cache_spec = [ord(c) for c in cache_res]
  396. expr_code = u' + '.join(gen_sig_code(cache_spec))
  397. code = u'if len(s) == %d:\n return %s\n' % (slen, expr_code)
  398. self.to_screen(u'Extracted signature function:\n' + code)
  399. def _parse_sig_js(self, jscode):
  400. funcname = self._search_regex(
  401. r'signature=([a-zA-Z]+)', jscode,
  402. u'Initial JS player signature function name')
  403. jsi = JSInterpreter(jscode)
  404. initial_function = jsi.extract_function(funcname)
  405. return lambda s: initial_function([s])
  406. def _parse_sig_swf(self, file_contents):
  407. if file_contents[1:3] != b'WS':
  408. raise ExtractorError(
  409. u'Not an SWF file; header is %r' % file_contents[:3])
  410. if file_contents[:1] == b'C':
  411. content = zlib.decompress(file_contents[8:])
  412. else:
  413. raise NotImplementedError(u'Unsupported compression format %r' %
  414. file_contents[:1])
  415. def extract_tags(content):
  416. pos = 0
  417. while pos < len(content):
  418. header16 = struct.unpack('<H', content[pos:pos+2])[0]
  419. pos += 2
  420. tag_code = header16 >> 6
  421. tag_len = header16 & 0x3f
  422. if tag_len == 0x3f:
  423. tag_len = struct.unpack('<I', content[pos:pos+4])[0]
  424. pos += 4
  425. assert pos+tag_len <= len(content)
  426. yield (tag_code, content[pos:pos+tag_len])
  427. pos += tag_len
  428. code_tag = next(tag
  429. for tag_code, tag in extract_tags(content)
  430. if tag_code == 82)
  431. p = code_tag.index(b'\0', 4) + 1
  432. code_reader = io.BytesIO(code_tag[p:])
  433. # Parse ABC (AVM2 ByteCode)
  434. def read_int(reader=None):
  435. if reader is None:
  436. reader = code_reader
  437. res = 0
  438. shift = 0
  439. for _ in range(5):
  440. buf = reader.read(1)
  441. assert len(buf) == 1
  442. b = struct.unpack('<B', buf)[0]
  443. res = res | ((b & 0x7f) << shift)
  444. if b & 0x80 == 0:
  445. break
  446. shift += 7
  447. return res
  448. def u30(reader=None):
  449. res = read_int(reader)
  450. assert res & 0xf0000000 == 0
  451. return res
  452. u32 = read_int
  453. def s32(reader=None):
  454. v = read_int(reader)
  455. if v & 0x80000000 != 0:
  456. v = - ((v ^ 0xffffffff) + 1)
  457. return v
  458. def read_string(reader=None):
  459. if reader is None:
  460. reader = code_reader
  461. slen = u30(reader)
  462. resb = reader.read(slen)
  463. assert len(resb) == slen
  464. return resb.decode('utf-8')
  465. def read_bytes(count, reader=None):
  466. if reader is None:
  467. reader = code_reader
  468. resb = reader.read(count)
  469. assert len(resb) == count
  470. return resb
  471. def read_byte(reader=None):
  472. resb = read_bytes(1, reader=reader)
  473. res = struct.unpack('<B', resb)[0]
  474. return res
  475. # minor_version + major_version
  476. read_bytes(2 + 2)
  477. # Constant pool
  478. int_count = u30()
  479. for _c in range(1, int_count):
  480. s32()
  481. uint_count = u30()
  482. for _c in range(1, uint_count):
  483. u32()
  484. double_count = u30()
  485. read_bytes((double_count-1) * 8)
  486. string_count = u30()
  487. constant_strings = [u'']
  488. for _c in range(1, string_count):
  489. s = read_string()
  490. constant_strings.append(s)
  491. namespace_count = u30()
  492. for _c in range(1, namespace_count):
  493. read_bytes(1) # kind
  494. u30() # name
  495. ns_set_count = u30()
  496. for _c in range(1, ns_set_count):
  497. count = u30()
  498. for _c2 in range(count):
  499. u30()
  500. multiname_count = u30()
  501. MULTINAME_SIZES = {
  502. 0x07: 2, # QName
  503. 0x0d: 2, # QNameA
  504. 0x0f: 1, # RTQName
  505. 0x10: 1, # RTQNameA
  506. 0x11: 0, # RTQNameL
  507. 0x12: 0, # RTQNameLA
  508. 0x09: 2, # Multiname
  509. 0x0e: 2, # MultinameA
  510. 0x1b: 1, # MultinameL
  511. 0x1c: 1, # MultinameLA
  512. }
  513. multinames = [u'']
  514. for _c in range(1, multiname_count):
  515. kind = u30()
  516. assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
  517. if kind == 0x07:
  518. u30() # namespace_idx
  519. name_idx = u30()
  520. multinames.append(constant_strings[name_idx])
  521. else:
  522. multinames.append('[MULTINAME kind: %d]' % kind)
  523. for _c2 in range(MULTINAME_SIZES[kind]):
  524. u30()
  525. # Methods
  526. method_count = u30()
  527. MethodInfo = collections.namedtuple(
  528. 'MethodInfo',
  529. ['NEED_ARGUMENTS', 'NEED_REST'])
  530. method_infos = []
  531. for method_id in range(method_count):
  532. param_count = u30()
  533. u30() # return type
  534. for _ in range(param_count):
  535. u30() # param type
  536. u30() # name index (always 0 for youtube)
  537. flags = read_byte()
  538. if flags & 0x08 != 0:
  539. # Options present
  540. option_count = u30()
  541. for c in range(option_count):
  542. u30() # val
  543. read_bytes(1) # kind
  544. if flags & 0x80 != 0:
  545. # Param names present
  546. for _ in range(param_count):
  547. u30() # param name
  548. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  549. method_infos.append(mi)
  550. # Metadata
  551. metadata_count = u30()
  552. for _c in range(metadata_count):
  553. u30() # name
  554. item_count = u30()
  555. for _c2 in range(item_count):
  556. u30() # key
  557. u30() # value
  558. def parse_traits_info():
  559. trait_name_idx = u30()
  560. kind_full = read_byte()
  561. kind = kind_full & 0x0f
  562. attrs = kind_full >> 4
  563. methods = {}
  564. if kind in [0x00, 0x06]: # Slot or Const
  565. u30() # Slot id
  566. u30() # type_name_idx
  567. vindex = u30()
  568. if vindex != 0:
  569. read_byte() # vkind
  570. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  571. u30() # disp_id
  572. method_idx = u30()
  573. methods[multinames[trait_name_idx]] = method_idx
  574. elif kind == 0x04: # Class
  575. u30() # slot_id
  576. u30() # classi
  577. elif kind == 0x05: # Function
  578. u30() # slot_id
  579. function_idx = u30()
  580. methods[function_idx] = multinames[trait_name_idx]
  581. else:
  582. raise ExtractorError(u'Unsupported trait kind %d' % kind)
  583. if attrs & 0x4 != 0: # Metadata present
  584. metadata_count = u30()
  585. for _c3 in range(metadata_count):
  586. u30() # metadata index
  587. return methods
  588. # Classes
  589. TARGET_CLASSNAME = u'SignatureDecipher'
  590. searched_idx = multinames.index(TARGET_CLASSNAME)
  591. searched_class_id = None
  592. class_count = u30()
  593. for class_id in range(class_count):
  594. name_idx = u30()
  595. if name_idx == searched_idx:
  596. # We found the class we're looking for!
  597. searched_class_id = class_id
  598. u30() # super_name idx
  599. flags = read_byte()
  600. if flags & 0x08 != 0: # Protected namespace is present
  601. u30() # protected_ns_idx
  602. intrf_count = u30()
  603. for _c2 in range(intrf_count):
  604. u30()
  605. u30() # iinit
  606. trait_count = u30()
  607. for _c2 in range(trait_count):
  608. parse_traits_info()
  609. if searched_class_id is None:
  610. raise ExtractorError(u'Target class %r not found' %
  611. TARGET_CLASSNAME)
  612. method_names = {}
  613. method_idxs = {}
  614. for class_id in range(class_count):
  615. u30() # cinit
  616. trait_count = u30()
  617. for _c2 in range(trait_count):
  618. trait_methods = parse_traits_info()
  619. if class_id == searched_class_id:
  620. method_names.update(trait_methods.items())
  621. method_idxs.update(dict(
  622. (idx, name)
  623. for name, idx in trait_methods.items()))
  624. # Scripts
  625. script_count = u30()
  626. for _c in range(script_count):
  627. u30() # init
  628. trait_count = u30()
  629. for _c2 in range(trait_count):
  630. parse_traits_info()
  631. # Method bodies
  632. method_body_count = u30()
  633. Method = collections.namedtuple('Method', ['code', 'local_count'])
  634. methods = {}
  635. for _c in range(method_body_count):
  636. method_idx = u30()
  637. u30() # max_stack
  638. local_count = u30()
  639. u30() # init_scope_depth
  640. u30() # max_scope_depth
  641. code_length = u30()
  642. code = read_bytes(code_length)
  643. if method_idx in method_idxs:
  644. m = Method(code, local_count)
  645. methods[method_idxs[method_idx]] = m
  646. exception_count = u30()
  647. for _c2 in range(exception_count):
  648. u30() # from
  649. u30() # to
  650. u30() # target
  651. u30() # exc_type
  652. u30() # var_name
  653. trait_count = u30()
  654. for _c2 in range(trait_count):
  655. parse_traits_info()
  656. assert p + code_reader.tell() == len(code_tag)
  657. assert len(methods) == len(method_idxs)
  658. method_pyfunctions = {}
  659. def extract_function(func_name):
  660. if func_name in method_pyfunctions:
  661. return method_pyfunctions[func_name]
  662. if func_name not in methods:
  663. raise ExtractorError(u'Cannot find function %r' % func_name)
  664. m = methods[func_name]
  665. def resfunc(args):
  666. registers = ['(this)'] + list(args) + [None] * m.local_count
  667. stack = []
  668. coder = io.BytesIO(m.code)
  669. while True:
  670. opcode = struct.unpack('!B', coder.read(1))[0]
  671. if opcode == 36: # pushbyte
  672. v = struct.unpack('!B', coder.read(1))[0]
  673. stack.append(v)
  674. elif opcode == 44: # pushstring
  675. idx = u30(coder)
  676. stack.append(constant_strings[idx])
  677. elif opcode == 48: # pushscope
  678. # We don't implement the scope register, so we'll just
  679. # ignore the popped value
  680. stack.pop()
  681. elif opcode == 70: # callproperty
  682. index = u30(coder)
  683. mname = multinames[index]
  684. arg_count = u30(coder)
  685. args = list(reversed(
  686. [stack.pop() for _ in range(arg_count)]))
  687. obj = stack.pop()
  688. if mname == u'split':
  689. assert len(args) == 1
  690. assert isinstance(args[0], compat_str)
  691. assert isinstance(obj, compat_str)
  692. if args[0] == u'':
  693. res = list(obj)
  694. else:
  695. res = obj.split(args[0])
  696. stack.append(res)
  697. elif mname == u'slice':
  698. assert len(args) == 1
  699. assert isinstance(args[0], int)
  700. assert isinstance(obj, list)
  701. res = obj[args[0]:]
  702. stack.append(res)
  703. elif mname == u'join':
  704. assert len(args) == 1
  705. assert isinstance(args[0], compat_str)
  706. assert isinstance(obj, list)
  707. res = args[0].join(obj)
  708. stack.append(res)
  709. elif mname in method_pyfunctions:
  710. stack.append(method_pyfunctions[mname](args))
  711. else:
  712. raise NotImplementedError(
  713. u'Unsupported property %r on %r'
  714. % (mname, obj))
  715. elif opcode == 72: # returnvalue
  716. res = stack.pop()
  717. return res
  718. elif opcode == 79: # callpropvoid
  719. index = u30(coder)
  720. mname = multinames[index]
  721. arg_count = u30(coder)
  722. args = list(reversed(
  723. [stack.pop() for _ in range(arg_count)]))
  724. obj = stack.pop()
  725. if mname == u'reverse':
  726. assert isinstance(obj, list)
  727. obj.reverse()
  728. else:
  729. raise NotImplementedError(
  730. u'Unsupported (void) property %r on %r'
  731. % (mname, obj))
  732. elif opcode == 93: # findpropstrict
  733. index = u30(coder)
  734. mname = multinames[index]
  735. res = extract_function(mname)
  736. stack.append(res)
  737. elif opcode == 97: # setproperty
  738. index = u30(coder)
  739. value = stack.pop()
  740. idx = stack.pop()
  741. obj = stack.pop()
  742. assert isinstance(obj, list)
  743. assert isinstance(idx, int)
  744. obj[idx] = value
  745. elif opcode == 98: # getlocal
  746. index = u30(coder)
  747. stack.append(registers[index])
  748. elif opcode == 99: # setlocal
  749. index = u30(coder)
  750. value = stack.pop()
  751. registers[index] = value
  752. elif opcode == 102: # getproperty
  753. index = u30(coder)
  754. pname = multinames[index]
  755. if pname == u'length':
  756. obj = stack.pop()
  757. assert isinstance(obj, list)
  758. stack.append(len(obj))
  759. else: # Assume attribute access
  760. idx = stack.pop()
  761. assert isinstance(idx, int)
  762. obj = stack.pop()
  763. assert isinstance(obj, list)
  764. stack.append(obj[idx])
  765. elif opcode == 128: # coerce
  766. u30(coder)
  767. elif opcode == 133: # coerce_s
  768. assert isinstance(stack[-1], (type(None), compat_str))
  769. elif opcode == 164: # modulo
  770. value2 = stack.pop()
  771. value1 = stack.pop()
  772. res = value1 % value2
  773. stack.append(res)
  774. elif opcode == 208: # getlocal_0
  775. stack.append(registers[0])
  776. elif opcode == 209: # getlocal_1
  777. stack.append(registers[1])
  778. elif opcode == 210: # getlocal_2
  779. stack.append(registers[2])
  780. elif opcode == 211: # getlocal_3
  781. stack.append(registers[3])
  782. elif opcode == 214: # setlocal_2
  783. registers[2] = stack.pop()
  784. elif opcode == 215: # setlocal_3
  785. registers[3] = stack.pop()
  786. else:
  787. raise NotImplementedError(
  788. u'Unsupported opcode %d' % opcode)
  789. method_pyfunctions[func_name] = resfunc
  790. return resfunc
  791. initial_function = extract_function(u'decipher')
  792. return lambda s: initial_function([s])
  793. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  794. """Turn the encrypted s field into a working signature"""
  795. if player_url is not None:
  796. if player_url.startswith(u'//'):
  797. player_url = u'https:' + player_url
  798. try:
  799. player_id = (player_url, len(s))
  800. if player_id not in self._player_cache:
  801. func = self._extract_signature_function(
  802. video_id, player_url, len(s)
  803. )
  804. self._player_cache[player_id] = func
  805. func = self._player_cache[player_id]
  806. if self._downloader.params.get('youtube_print_sig_code'):
  807. self._print_sig_code(func, len(s))
  808. return func(s)
  809. except Exception:
  810. tb = traceback.format_exc()
  811. self._downloader.report_warning(
  812. u'Automatic signature extraction failed: ' + tb)
  813. self._downloader.report_warning(
  814. u'Warning: Falling back to static signature algorithm')
  815. return self._static_decrypt_signature(
  816. s, video_id, player_url, age_gate)
  817. def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
  818. if age_gate:
  819. # The videos with age protection use another player, so the
  820. # algorithms can be different.
  821. if len(s) == 86:
  822. return s[2:63] + s[82] + s[64:82] + s[63]
  823. if len(s) == 93:
  824. return s[86:29:-1] + s[88] + s[28:5:-1]
  825. elif len(s) == 92:
  826. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  827. elif len(s) == 91:
  828. return s[84:27:-1] + s[86] + s[26:5:-1]
  829. elif len(s) == 90:
  830. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  831. elif len(s) == 89:
  832. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  833. elif len(s) == 88:
  834. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  835. elif len(s) == 87:
  836. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  837. elif len(s) == 86:
  838. return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
  839. elif len(s) == 85:
  840. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  841. elif len(s) == 84:
  842. return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
  843. elif len(s) == 83:
  844. return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
  845. elif len(s) == 82:
  846. return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
  847. elif len(s) == 81:
  848. 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]
  849. elif len(s) == 80:
  850. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  851. elif len(s) == 79:
  852. 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]
  853. else:
  854. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  855. def _get_available_subtitles(self, video_id, webpage):
  856. try:
  857. sub_list = self._download_webpage(
  858. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  859. video_id, note=False)
  860. except ExtractorError as err:
  861. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  862. return {}
  863. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  864. sub_lang_list = {}
  865. for l in lang_list:
  866. lang = l[1]
  867. params = compat_urllib_parse.urlencode({
  868. 'lang': lang,
  869. 'v': video_id,
  870. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  871. 'name': unescapeHTML(l[0]).encode('utf-8'),
  872. })
  873. url = u'https://www.youtube.com/api/timedtext?' + params
  874. sub_lang_list[lang] = url
  875. if not sub_lang_list:
  876. self._downloader.report_warning(u'video doesn\'t have subtitles')
  877. return {}
  878. return sub_lang_list
  879. def _get_available_automatic_caption(self, video_id, webpage):
  880. """We need the webpage for getting the captions url, pass it as an
  881. argument to speed up the process."""
  882. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  883. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  884. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  885. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  886. if mobj is None:
  887. self._downloader.report_warning(err_msg)
  888. return {}
  889. player_config = json.loads(mobj.group(1))
  890. try:
  891. args = player_config[u'args']
  892. caption_url = args[u'ttsurl']
  893. timestamp = args[u'timestamp']
  894. # We get the available subtitles
  895. list_params = compat_urllib_parse.urlencode({
  896. 'type': 'list',
  897. 'tlangs': 1,
  898. 'asrs': 1,
  899. })
  900. list_url = caption_url + '&' + list_params
  901. caption_list = self._download_xml(list_url, video_id)
  902. original_lang_node = caption_list.find('track')
  903. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  904. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  905. return {}
  906. original_lang = original_lang_node.attrib['lang_code']
  907. sub_lang_list = {}
  908. for lang_node in caption_list.findall('target'):
  909. sub_lang = lang_node.attrib['lang_code']
  910. params = compat_urllib_parse.urlencode({
  911. 'lang': original_lang,
  912. 'tlang': sub_lang,
  913. 'fmt': sub_format,
  914. 'ts': timestamp,
  915. 'kind': 'asr',
  916. })
  917. sub_lang_list[sub_lang] = caption_url + '&' + params
  918. return sub_lang_list
  919. # An extractor error can be raise by the download process if there are
  920. # no automatic captions but there are subtitles
  921. except (KeyError, ExtractorError):
  922. self._downloader.report_warning(err_msg)
  923. return {}
  924. @classmethod
  925. def extract_id(cls, url):
  926. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  927. if mobj is None:
  928. raise ExtractorError(u'Invalid URL: %s' % url)
  929. video_id = mobj.group(2)
  930. return video_id
  931. def _extract_from_m3u8(self, manifest_url, video_id):
  932. url_map = {}
  933. def _get_urls(_manifest):
  934. lines = _manifest.split('\n')
  935. urls = filter(lambda l: l and not l.startswith('#'),
  936. lines)
  937. return urls
  938. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  939. formats_urls = _get_urls(manifest)
  940. for format_url in formats_urls:
  941. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  942. url_map[itag] = format_url
  943. return url_map
  944. def _extract_annotations(self, video_id):
  945. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  946. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  947. def _real_extract(self, url):
  948. proto = (
  949. u'http' if self._downloader.params.get('prefer_insecure', False)
  950. else u'https')
  951. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  952. mobj = re.search(self._NEXT_URL_RE, url)
  953. if mobj:
  954. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  955. video_id = self.extract_id(url)
  956. # Get video webpage
  957. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  958. video_webpage = self._download_webpage(url, video_id)
  959. # Attempt to extract SWF player URL
  960. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  961. if mobj is not None:
  962. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  963. else:
  964. player_url = None
  965. # Get video info
  966. self.report_video_info_webpage_download(video_id)
  967. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  968. self.report_age_confirmation()
  969. age_gate = True
  970. # We simulate the access to the video from www.youtube.com/v/{video_id}
  971. # this can be viewed without login into Youtube
  972. data = compat_urllib_parse.urlencode({'video_id': video_id,
  973. 'el': 'player_embedded',
  974. 'gl': 'US',
  975. 'hl': 'en',
  976. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  977. 'asv': 3,
  978. 'sts':'1588',
  979. })
  980. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  981. video_info_webpage = self._download_webpage(video_info_url, video_id,
  982. note=False,
  983. errnote='unable to download video info webpage')
  984. video_info = compat_parse_qs(video_info_webpage)
  985. else:
  986. age_gate = False
  987. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  988. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  989. % (video_id, el_type))
  990. video_info_webpage = self._download_webpage(video_info_url, video_id,
  991. note=False,
  992. errnote='unable to download video info webpage')
  993. video_info = compat_parse_qs(video_info_webpage)
  994. if 'token' in video_info:
  995. break
  996. if 'token' not in video_info:
  997. if 'reason' in video_info:
  998. raise ExtractorError(
  999. u'YouTube said: %s' % video_info['reason'][0],
  1000. expected=True, video_id=video_id)
  1001. else:
  1002. raise ExtractorError(
  1003. u'"token" parameter not in video info for unknown reason',
  1004. video_id=video_id)
  1005. if 'view_count' in video_info:
  1006. view_count = int(video_info['view_count'][0])
  1007. else:
  1008. view_count = None
  1009. # Check for "rental" videos
  1010. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1011. raise ExtractorError(u'"rental" videos not supported')
  1012. # Start extracting information
  1013. self.report_information_extraction(video_id)
  1014. # uploader
  1015. if 'author' not in video_info:
  1016. raise ExtractorError(u'Unable to extract uploader name')
  1017. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1018. # uploader_id
  1019. video_uploader_id = None
  1020. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1021. if mobj is not None:
  1022. video_uploader_id = mobj.group(1)
  1023. else:
  1024. self._downloader.report_warning(u'unable to extract uploader nickname')
  1025. # title
  1026. if 'title' in video_info:
  1027. video_title = video_info['title'][0]
  1028. else:
  1029. self._downloader.report_warning(u'Unable to extract video title')
  1030. video_title = u'_'
  1031. # thumbnail image
  1032. # We try first to get a high quality image:
  1033. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1034. video_webpage, re.DOTALL)
  1035. if m_thumb is not None:
  1036. video_thumbnail = m_thumb.group(1)
  1037. elif 'thumbnail_url' not in video_info:
  1038. self._downloader.report_warning(u'unable to extract video thumbnail')
  1039. video_thumbnail = None
  1040. else: # don't panic if we can't find it
  1041. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1042. # upload date
  1043. upload_date = None
  1044. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  1045. if mobj is None:
  1046. mobj = re.search(
  1047. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  1048. video_webpage)
  1049. if mobj is not None:
  1050. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1051. upload_date = unified_strdate(upload_date)
  1052. m_cat_container = get_element_by_id("eow-category", video_webpage)
  1053. if m_cat_container:
  1054. category = self._html_search_regex(
  1055. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1056. default=None)
  1057. video_categories = None if category is None else [category]
  1058. else:
  1059. video_categories = None
  1060. # description
  1061. video_description = get_element_by_id("eow-description", video_webpage)
  1062. if video_description:
  1063. video_description = re.sub(r'''(?x)
  1064. <a\s+
  1065. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1066. title="([^"]+)"\s+
  1067. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1068. class="yt-uix-redirect-link"\s*>
  1069. [^<]+
  1070. </a>
  1071. ''', r'\1', video_description)
  1072. video_description = clean_html(video_description)
  1073. else:
  1074. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1075. if fd_mobj:
  1076. video_description = unescapeHTML(fd_mobj.group(1))
  1077. else:
  1078. video_description = u''
  1079. def _extract_count(klass):
  1080. count = self._search_regex(
  1081. r'class="%s">([\d,]+)</span>' % re.escape(klass),
  1082. video_webpage, klass, default=None)
  1083. if count is not None:
  1084. return int(count.replace(',', ''))
  1085. return None
  1086. like_count = _extract_count(u'likes-count')
  1087. dislike_count = _extract_count(u'dislikes-count')
  1088. # subtitles
  1089. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1090. if self._downloader.params.get('listsubtitles', False):
  1091. self._list_available_subtitles(video_id, video_webpage)
  1092. return
  1093. if 'length_seconds' not in video_info:
  1094. self._downloader.report_warning(u'unable to extract video duration')
  1095. video_duration = None
  1096. else:
  1097. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  1098. # annotations
  1099. video_annotations = None
  1100. if self._downloader.params.get('writeannotations', False):
  1101. video_annotations = self._extract_annotations(video_id)
  1102. # Decide which formats to download
  1103. try:
  1104. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  1105. if not mobj:
  1106. raise ValueError('Could not find vevo ID')
  1107. json_code = uppercase_escape(mobj.group(1))
  1108. ytplayer_config = json.loads(json_code)
  1109. args = ytplayer_config['args']
  1110. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1111. # this signatures are encrypted
  1112. if 'url_encoded_fmt_stream_map' not in args:
  1113. raise ValueError(u'No stream_map present') # caught below
  1114. re_signature = re.compile(r'[&,]s=')
  1115. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  1116. if m_s is not None:
  1117. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1118. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1119. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  1120. if m_s is not None:
  1121. if 'adaptive_fmts' in video_info:
  1122. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  1123. else:
  1124. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  1125. except ValueError:
  1126. pass
  1127. def _map_to_format_list(urlmap):
  1128. formats = []
  1129. for itag, video_real_url in urlmap.items():
  1130. dct = {
  1131. 'format_id': itag,
  1132. 'url': video_real_url,
  1133. 'player_url': player_url,
  1134. }
  1135. if itag in self._formats:
  1136. dct.update(self._formats[itag])
  1137. formats.append(dct)
  1138. return formats
  1139. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1140. self.report_rtmp_download()
  1141. formats = [{
  1142. 'format_id': '_rtmp',
  1143. 'protocol': 'rtmp',
  1144. 'url': video_info['conn'][0],
  1145. 'player_url': player_url,
  1146. }]
  1147. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  1148. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  1149. if 'rtmpe%3Dyes' in encoded_url_map:
  1150. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1151. url_map = {}
  1152. for url_data_str in encoded_url_map.split(','):
  1153. url_data = compat_parse_qs(url_data_str)
  1154. if 'itag' in url_data and 'url' in url_data:
  1155. url = url_data['url'][0]
  1156. if 'sig' in url_data:
  1157. url += '&signature=' + url_data['sig'][0]
  1158. elif 's' in url_data:
  1159. encrypted_sig = url_data['s'][0]
  1160. if self._downloader.params.get('verbose'):
  1161. if age_gate:
  1162. if player_url is None:
  1163. player_version = 'unknown'
  1164. else:
  1165. player_version = self._search_regex(
  1166. r'-(.+)\.swf$', player_url,
  1167. u'flash player', fatal=False)
  1168. player_desc = 'flash player %s' % player_version
  1169. else:
  1170. player_version = self._search_regex(
  1171. r'html5player-(.+?)\.js', video_webpage,
  1172. 'html5 player', fatal=False)
  1173. player_desc = u'html5 player %s' % player_version
  1174. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1175. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1176. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1177. if not age_gate:
  1178. jsplayer_url_json = self._search_regex(
  1179. r'"assets":.+?"js":\s*("[^"]+")',
  1180. video_webpage, u'JS player URL')
  1181. player_url = json.loads(jsplayer_url_json)
  1182. signature = self._decrypt_signature(
  1183. encrypted_sig, video_id, player_url, age_gate)
  1184. url += '&signature=' + signature
  1185. if 'ratebypass' not in url:
  1186. url += '&ratebypass=yes'
  1187. url_map[url_data['itag'][0]] = url
  1188. formats = _map_to_format_list(url_map)
  1189. elif video_info.get('hlsvp'):
  1190. manifest_url = video_info['hlsvp'][0]
  1191. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1192. formats = _map_to_format_list(url_map)
  1193. else:
  1194. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1195. # Look for the DASH manifest
  1196. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  1197. try:
  1198. # The DASH manifest used needs to be the one from the original video_webpage.
  1199. # The one found in get_video_info seems to be using different signatures.
  1200. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  1201. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  1202. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  1203. if age_gate:
  1204. dash_manifest_url = video_info.get('dashmpd')[0]
  1205. else:
  1206. dash_manifest_url = ytplayer_config['args']['dashmpd']
  1207. def decrypt_sig(mobj):
  1208. s = mobj.group(1)
  1209. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  1210. return '/signature/%s' % dec_s
  1211. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  1212. dash_doc = self._download_xml(
  1213. dash_manifest_url, video_id,
  1214. note=u'Downloading DASH manifest',
  1215. errnote=u'Could not download DASH manifest')
  1216. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  1217. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  1218. if url_el is None:
  1219. continue
  1220. format_id = r.attrib['id']
  1221. video_url = url_el.text
  1222. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  1223. f = {
  1224. 'format_id': format_id,
  1225. 'url': video_url,
  1226. 'width': int_or_none(r.attrib.get('width')),
  1227. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  1228. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  1229. 'filesize': filesize,
  1230. }
  1231. try:
  1232. existing_format = next(
  1233. fo for fo in formats
  1234. if fo['format_id'] == format_id)
  1235. except StopIteration:
  1236. f.update(self._formats.get(format_id, {}))
  1237. formats.append(f)
  1238. else:
  1239. existing_format.update(f)
  1240. except (ExtractorError, KeyError) as e:
  1241. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  1242. self._sort_formats(formats)
  1243. return {
  1244. 'id': video_id,
  1245. 'uploader': video_uploader,
  1246. 'uploader_id': video_uploader_id,
  1247. 'upload_date': upload_date,
  1248. 'title': video_title,
  1249. 'thumbnail': video_thumbnail,
  1250. 'description': video_description,
  1251. 'categories': video_categories,
  1252. 'subtitles': video_subtitles,
  1253. 'duration': video_duration,
  1254. 'age_limit': 18 if age_gate else 0,
  1255. 'annotations': video_annotations,
  1256. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1257. 'view_count': view_count,
  1258. 'like_count': like_count,
  1259. 'dislike_count': dislike_count,
  1260. 'formats': formats,
  1261. }
  1262. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1263. IE_DESC = u'YouTube.com playlists'
  1264. _VALID_URL = r"""(?x)(?:
  1265. (?:https?://)?
  1266. (?:\w+\.)?
  1267. youtube\.com/
  1268. (?:
  1269. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1270. \? (?:.*?&)*? (?:p|a|list)=
  1271. | p/
  1272. )
  1273. (
  1274. (?:PL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  1275. # Top tracks, they can also include dots
  1276. |(?:MC)[\w\.]*
  1277. )
  1278. .*
  1279. |
  1280. ((?:PL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  1281. )"""
  1282. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1283. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  1284. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1285. IE_NAME = u'youtube:playlist'
  1286. def _real_initialize(self):
  1287. self._login()
  1288. def _ids_to_results(self, ids):
  1289. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1290. for vid_id in ids]
  1291. def _extract_mix(self, playlist_id):
  1292. # The mixes are generated from a a single video
  1293. # the id of the playlist is just 'RD' + video_id
  1294. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1295. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  1296. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1297. title_span = (search_title('playlist-title') or
  1298. search_title('title long-title') or search_title('title'))
  1299. title = clean_html(title_span)
  1300. video_re = r'''(?x)data-video-username="(.*?)".*?
  1301. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id)
  1302. matches = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
  1303. # Some of the videos may have been deleted, their username field is empty
  1304. ids = [video_id for (username, video_id) in matches if username]
  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)