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.

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