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.

1404 lines
63 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 ..swfinterp import SWFInterpreter
  16. from ..utils import (
  17. compat_chr,
  18. compat_parse_qs,
  19. compat_urllib_parse,
  20. compat_urllib_request,
  21. compat_urlparse,
  22. compat_str,
  23. clean_html,
  24. get_cachedir,
  25. get_element_by_id,
  26. get_element_by_attribute,
  27. ExtractorError,
  28. int_or_none,
  29. PagedList,
  30. unescapeHTML,
  31. unified_strdate,
  32. orderedSet,
  33. write_json_file,
  34. uppercase_escape,
  35. )
  36. class YoutubeBaseInfoExtractor(InfoExtractor):
  37. """Provide base functions for Youtube extractors"""
  38. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  39. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  40. _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  41. _NETRC_MACHINE = 'youtube'
  42. # If True it will raise an error if no login info is provided
  43. _LOGIN_REQUIRED = False
  44. def _set_language(self):
  45. return bool(self._download_webpage(
  46. self._LANG_URL, None,
  47. note=u'Setting language', errnote='unable to set language',
  48. fatal=False))
  49. def _login(self):
  50. (username, password) = self._get_login_info()
  51. # No authentication to be performed
  52. if username is None:
  53. if self._LOGIN_REQUIRED:
  54. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  55. return False
  56. login_page = self._download_webpage(
  57. self._LOGIN_URL, None,
  58. note=u'Downloading login page',
  59. errnote=u'unable to fetch login page', fatal=False)
  60. if login_page is False:
  61. return
  62. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  63. login_page, u'Login GALX parameter')
  64. # Log in
  65. login_form_strs = {
  66. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  67. u'Email': username,
  68. u'GALX': galx,
  69. u'Passwd': password,
  70. u'PersistentCookie': u'yes',
  71. u'_utf8': u'',
  72. u'bgresponse': u'js_disabled',
  73. u'checkConnection': u'',
  74. u'checkedDomains': u'youtube',
  75. u'dnConn': u'',
  76. u'pstMsg': u'0',
  77. u'rmShown': u'1',
  78. u'secTok': u'',
  79. u'signIn': u'Sign in',
  80. u'timeStmp': u'',
  81. u'service': u'youtube',
  82. u'uilel': u'3',
  83. u'hl': u'en_US',
  84. }
  85. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  86. # chokes on unicode
  87. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  88. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  89. req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  90. login_results = self._download_webpage(
  91. req, None,
  92. note=u'Logging in', errnote=u'unable to log in', fatal=False)
  93. if login_results is False:
  94. return False
  95. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  96. self._downloader.report_warning(u'unable to log in: bad username or password')
  97. return False
  98. return True
  99. def _confirm_age(self):
  100. age_form = {
  101. 'next_url': '/',
  102. 'action_confirm': 'Confirm',
  103. }
  104. req = compat_urllib_request.Request(self._AGE_URL,
  105. compat_urllib_parse.urlencode(age_form).encode('ascii'))
  106. self._download_webpage(
  107. req, None,
  108. note=u'Confirming age', errnote=u'Unable to confirm age')
  109. return True
  110. def _real_initialize(self):
  111. if self._downloader is None:
  112. return
  113. if not self._set_language():
  114. return
  115. if not self._login():
  116. return
  117. self._confirm_age()
  118. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  119. IE_DESC = u'YouTube.com'
  120. _VALID_URL = r"""(?x)^
  121. (
  122. (?:https?://|//)? # http(s):// or protocol-independent URL (optional)
  123. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  124. (?:www\.)?deturl\.com/www\.youtube\.com/|
  125. (?:www\.)?pwnyoutube\.com/|
  126. (?:www\.)?yourepeat\.com/|
  127. tube\.majestyc\.net/|
  128. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  129. (?:.*?\#/)? # handle anchor (#/) redirect urls
  130. (?: # the various things that can precede the ID:
  131. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  132. |(?: # or the v= param in all its forms
  133. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  134. (?:\?|\#!?) # the params delimiter ? or # or #!
  135. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  136. v=
  137. )
  138. ))
  139. |youtu\.be/ # just youtu.be/xxxx
  140. |https?://(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  141. )
  142. )? # all until now is optional -> you can pass the naked ID
  143. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  144. (?(1).+)? # if we found the ID, everything can follow
  145. $"""
  146. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  147. _formats = {
  148. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  149. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  150. '13': {'ext': '3gp'},
  151. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  152. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  153. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  154. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  155. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  156. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  157. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  158. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  159. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  160. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  161. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  162. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  163. # 3d videos
  164. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
  165. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
  166. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
  167. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
  168. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
  169. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
  170. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
  171. # Apple HTTP Live Streaming
  172. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  173. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
  174. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
  175. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
  176. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
  177. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  178. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
  179. # DASH mp4 video
  180. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  181. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  182. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  183. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  184. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  185. '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  186. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  187. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  188. # Dash mp4 audio
  189. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
  190. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
  191. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
  192. # Dash webm
  193. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  194. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  195. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  196. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  197. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  198. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  199. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  200. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  201. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  202. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  203. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  204. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  205. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  206. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  207. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  208. # Dash webm audio
  209. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 48, 'preference': -50},
  210. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  211. # RTMP (unnamed)
  212. '_rtmp': {'protocol': 'rtmp'},
  213. }
  214. IE_NAME = u'youtube'
  215. _TESTS = [
  216. {
  217. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  218. u"file": u"BaW_jenozKc.mp4",
  219. u"info_dict": {
  220. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  221. u"uploader": u"Philipp Hagemeister",
  222. u"uploader_id": u"phihag",
  223. u"upload_date": u"20121002",
  224. 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 .",
  225. u"categories": [u'Science & Technology'],
  226. }
  227. },
  228. {
  229. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  230. u"file": u"UxxajLWwzqY.mp4",
  231. u"note": u"Test generic use_cipher_signature video (#897)",
  232. u"info_dict": {
  233. u"upload_date": u"20120506",
  234. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  235. u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
  236. u"uploader": u"Icona Pop",
  237. u"uploader_id": u"IconaPop"
  238. }
  239. },
  240. {
  241. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  242. u"file": u"07FYdnEawAQ.mp4",
  243. u"note": u"Test VEVO video with age protection (#956)",
  244. u"info_dict": {
  245. u"upload_date": u"20130703",
  246. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  247. u"description": u"md5:64249768eec3bc4276236606ea996373",
  248. u"uploader": u"justintimberlakeVEVO",
  249. u"uploader_id": u"justintimberlakeVEVO"
  250. }
  251. },
  252. {
  253. u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
  254. u"file": u"yZIXLfi8CZQ.mp4",
  255. u"note": u"Embed-only video (#1746)",
  256. u"info_dict": {
  257. u"upload_date": u"20120608",
  258. u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
  259. u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
  260. u"uploader": u"SET India",
  261. u"uploader_id": u"setindia"
  262. }
  263. },
  264. {
  265. u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
  266. u"file": u"a9LDPn-MO4I.m4a",
  267. u"note": u"256k DASH audio (format 141) via DASH manifest",
  268. u"info_dict": {
  269. u"upload_date": "20121002",
  270. u"uploader_id": "8KVIDEO",
  271. u"description": "No description available.",
  272. u"uploader": "8KVIDEO",
  273. u"title": "UHDTV TEST 8K VIDEO.mp4"
  274. },
  275. u"params": {
  276. u"youtube_include_dash_manifest": True,
  277. u"format": "141",
  278. },
  279. },
  280. # DASH manifest with encrypted signature
  281. {
  282. u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  283. u'info_dict': {
  284. u'id': u'IB3lcPjvWLA',
  285. u'ext': u'm4a',
  286. u'title': u'Afrojack - The Spark ft. Spree Wilson',
  287. u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8',
  288. u'uploader': u'AfrojackVEVO',
  289. u'uploader_id': u'AfrojackVEVO',
  290. u'upload_date': u'20131011',
  291. },
  292. u"params": {
  293. u'youtube_include_dash_manifest': True,
  294. u'format': '141',
  295. },
  296. },
  297. ]
  298. @classmethod
  299. def suitable(cls, url):
  300. """Receives a URL and returns True if suitable for this IE."""
  301. if YoutubePlaylistIE.suitable(url): return False
  302. return re.match(cls._VALID_URL, url) is not None
  303. def __init__(self, *args, **kwargs):
  304. super(YoutubeIE, self).__init__(*args, **kwargs)
  305. self._player_cache = {}
  306. def report_video_info_webpage_download(self, video_id):
  307. """Report attempt to download video info webpage."""
  308. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  309. def report_information_extraction(self, video_id):
  310. """Report attempt to extract video information."""
  311. self.to_screen(u'%s: Extracting video information' % video_id)
  312. def report_unavailable_format(self, video_id, format):
  313. """Report extracted video URL."""
  314. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  315. def report_rtmp_download(self):
  316. """Indicate the download will use the RTMP protocol."""
  317. self.to_screen(u'RTMP download detected')
  318. def _extract_signature_function(self, video_id, player_url, slen):
  319. id_m = re.match(
  320. r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3)?\.(?P<ext>[a-z]+)$',
  321. player_url)
  322. player_type = id_m.group('ext')
  323. player_id = id_m.group('id')
  324. # Read from filesystem cache
  325. func_id = '%s_%s_%d' % (player_type, player_id, slen)
  326. assert os.path.basename(func_id) == func_id
  327. cache_dir = get_cachedir(self._downloader.params)
  328. cache_enabled = cache_dir is not None
  329. if cache_enabled:
  330. cache_fn = os.path.join(os.path.expanduser(cache_dir),
  331. u'youtube-sigfuncs',
  332. func_id + '.json')
  333. try:
  334. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  335. cache_spec = json.load(cachef)
  336. return lambda s: u''.join(s[i] for i in cache_spec)
  337. except IOError:
  338. pass # No cache available
  339. if player_type == 'js':
  340. code = self._download_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. res = self._parse_sig_js(code)
  345. elif player_type == 'swf':
  346. urlh = self._request_webpage(
  347. player_url, video_id,
  348. note=u'Downloading %s player %s' % (player_type, player_id),
  349. errnote=u'Download of %s failed' % player_url)
  350. code = urlh.read()
  351. res = self._parse_sig_swf(code)
  352. else:
  353. assert False, 'Invalid player type %r' % player_type
  354. if cache_enabled:
  355. try:
  356. test_string = u''.join(map(compat_chr, range(slen)))
  357. cache_res = res(test_string)
  358. cache_spec = [ord(c) for c in cache_res]
  359. try:
  360. os.makedirs(os.path.dirname(cache_fn))
  361. except OSError as ose:
  362. if ose.errno != errno.EEXIST:
  363. raise
  364. write_json_file(cache_spec, cache_fn)
  365. except Exception:
  366. tb = traceback.format_exc()
  367. self._downloader.report_warning(
  368. u'Writing cache to %r failed: %s' % (cache_fn, tb))
  369. return res
  370. def _print_sig_code(self, func, slen):
  371. def gen_sig_code(idxs):
  372. def _genslice(start, end, step):
  373. starts = u'' if start == 0 else str(start)
  374. ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
  375. steps = u'' if step == 1 else (u':%d' % step)
  376. return u's[%s%s%s]' % (starts, ends, steps)
  377. step = None
  378. start = '(Never used)' # Quelch pyflakes warnings - start will be
  379. # set as soon as step is set
  380. for i, prev in zip(idxs[1:], idxs[:-1]):
  381. if step is not None:
  382. if i - prev == step:
  383. continue
  384. yield _genslice(start, prev, step)
  385. step = None
  386. continue
  387. if i - prev in [-1, 1]:
  388. step = i - prev
  389. start = prev
  390. continue
  391. else:
  392. yield u's[%d]' % prev
  393. if step is None:
  394. yield u's[%d]' % i
  395. else:
  396. yield _genslice(start, i, step)
  397. test_string = u''.join(map(compat_chr, range(slen)))
  398. cache_res = func(test_string)
  399. cache_spec = [ord(c) for c in cache_res]
  400. expr_code = u' + '.join(gen_sig_code(cache_spec))
  401. code = u'if len(s) == %d:\n return %s\n' % (slen, expr_code)
  402. self.to_screen(u'Extracted signature function:\n' + code)
  403. def _parse_sig_js(self, jscode):
  404. funcname = self._search_regex(
  405. r'signature=([$a-zA-Z]+)', jscode,
  406. u'Initial JS player signature function name')
  407. jsi = JSInterpreter(jscode)
  408. initial_function = jsi.extract_function(funcname)
  409. return lambda s: initial_function([s])
  410. def _parse_sig_swf(self, file_contents):
  411. swfi = SWFInterpreter(file_contents)
  412. TARGET_CLASSNAME = u'SignatureDecipher'
  413. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  414. initial_function = swfi.extract_function(searched_class, u'decipher')
  415. return lambda s: initial_function([s])
  416. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  417. """Turn the encrypted s field into a working signature"""
  418. if player_url is None:
  419. raise ExtractorError(u'Cannot decrypt signature without player_url')
  420. if player_url.startswith(u'//'):
  421. player_url = u'https:' + player_url
  422. try:
  423. player_id = (player_url, len(s))
  424. if player_id not in self._player_cache:
  425. func = self._extract_signature_function(
  426. video_id, player_url, len(s)
  427. )
  428. self._player_cache[player_id] = func
  429. func = self._player_cache[player_id]
  430. if self._downloader.params.get('youtube_print_sig_code'):
  431. self._print_sig_code(func, len(s))
  432. return func(s)
  433. except Exception as e:
  434. tb = traceback.format_exc()
  435. raise ExtractorError(
  436. u'Automatic signature extraction failed: ' + tb, cause=e)
  437. def _get_available_subtitles(self, video_id, webpage):
  438. try:
  439. sub_list = self._download_webpage(
  440. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  441. video_id, note=False)
  442. except ExtractorError as err:
  443. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  444. return {}
  445. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  446. sub_lang_list = {}
  447. for l in lang_list:
  448. lang = l[1]
  449. params = compat_urllib_parse.urlencode({
  450. 'lang': lang,
  451. 'v': video_id,
  452. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  453. 'name': unescapeHTML(l[0]).encode('utf-8'),
  454. })
  455. url = u'https://www.youtube.com/api/timedtext?' + params
  456. sub_lang_list[lang] = url
  457. if not sub_lang_list:
  458. self._downloader.report_warning(u'video doesn\'t have subtitles')
  459. return {}
  460. return sub_lang_list
  461. def _get_available_automatic_caption(self, video_id, webpage):
  462. """We need the webpage for getting the captions url, pass it as an
  463. argument to speed up the process."""
  464. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  465. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  466. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  467. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  468. if mobj is None:
  469. self._downloader.report_warning(err_msg)
  470. return {}
  471. player_config = json.loads(mobj.group(1))
  472. try:
  473. args = player_config[u'args']
  474. caption_url = args[u'ttsurl']
  475. timestamp = args[u'timestamp']
  476. # We get the available subtitles
  477. list_params = compat_urllib_parse.urlencode({
  478. 'type': 'list',
  479. 'tlangs': 1,
  480. 'asrs': 1,
  481. })
  482. list_url = caption_url + '&' + list_params
  483. caption_list = self._download_xml(list_url, video_id)
  484. original_lang_node = caption_list.find('track')
  485. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  486. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  487. return {}
  488. original_lang = original_lang_node.attrib['lang_code']
  489. sub_lang_list = {}
  490. for lang_node in caption_list.findall('target'):
  491. sub_lang = lang_node.attrib['lang_code']
  492. params = compat_urllib_parse.urlencode({
  493. 'lang': original_lang,
  494. 'tlang': sub_lang,
  495. 'fmt': sub_format,
  496. 'ts': timestamp,
  497. 'kind': 'asr',
  498. })
  499. sub_lang_list[sub_lang] = caption_url + '&' + params
  500. return sub_lang_list
  501. # An extractor error can be raise by the download process if there are
  502. # no automatic captions but there are subtitles
  503. except (KeyError, ExtractorError):
  504. self._downloader.report_warning(err_msg)
  505. return {}
  506. @classmethod
  507. def extract_id(cls, url):
  508. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  509. if mobj is None:
  510. raise ExtractorError(u'Invalid URL: %s' % url)
  511. video_id = mobj.group(2)
  512. return video_id
  513. def _extract_from_m3u8(self, manifest_url, video_id):
  514. url_map = {}
  515. def _get_urls(_manifest):
  516. lines = _manifest.split('\n')
  517. urls = filter(lambda l: l and not l.startswith('#'),
  518. lines)
  519. return urls
  520. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  521. formats_urls = _get_urls(manifest)
  522. for format_url in formats_urls:
  523. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  524. url_map[itag] = format_url
  525. return url_map
  526. def _extract_annotations(self, video_id):
  527. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  528. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  529. def _real_extract(self, url):
  530. proto = (
  531. u'http' if self._downloader.params.get('prefer_insecure', False)
  532. else u'https')
  533. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  534. mobj = re.search(self._NEXT_URL_RE, url)
  535. if mobj:
  536. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  537. video_id = self.extract_id(url)
  538. # Get video webpage
  539. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  540. video_webpage = self._download_webpage(url, video_id)
  541. # Attempt to extract SWF player URL
  542. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  543. if mobj is not None:
  544. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  545. else:
  546. player_url = None
  547. # Get video info
  548. self.report_video_info_webpage_download(video_id)
  549. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  550. self.report_age_confirmation()
  551. age_gate = True
  552. # We simulate the access to the video from www.youtube.com/v/{video_id}
  553. # this can be viewed without login into Youtube
  554. data = compat_urllib_parse.urlencode({
  555. 'video_id': video_id,
  556. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  557. 'sts':'16268',
  558. })
  559. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  560. video_info_webpage = self._download_webpage(video_info_url, video_id,
  561. note=False,
  562. errnote='unable to download video info webpage')
  563. video_info = compat_parse_qs(video_info_webpage)
  564. else:
  565. age_gate = False
  566. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  567. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  568. % (video_id, el_type))
  569. video_info_webpage = self._download_webpage(video_info_url, video_id,
  570. note=False,
  571. errnote='unable to download video info webpage')
  572. video_info = compat_parse_qs(video_info_webpage)
  573. if 'token' in video_info:
  574. break
  575. if 'token' not in video_info:
  576. if 'reason' in video_info:
  577. raise ExtractorError(
  578. u'YouTube said: %s' % video_info['reason'][0],
  579. expected=True, video_id=video_id)
  580. else:
  581. raise ExtractorError(
  582. u'"token" parameter not in video info for unknown reason',
  583. video_id=video_id)
  584. if 'view_count' in video_info:
  585. view_count = int(video_info['view_count'][0])
  586. else:
  587. view_count = None
  588. # Check for "rental" videos
  589. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  590. raise ExtractorError(u'"rental" videos not supported')
  591. # Start extracting information
  592. self.report_information_extraction(video_id)
  593. # uploader
  594. if 'author' not in video_info:
  595. raise ExtractorError(u'Unable to extract uploader name')
  596. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  597. # uploader_id
  598. video_uploader_id = None
  599. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  600. if mobj is not None:
  601. video_uploader_id = mobj.group(1)
  602. else:
  603. self._downloader.report_warning(u'unable to extract uploader nickname')
  604. # title
  605. if 'title' in video_info:
  606. video_title = video_info['title'][0]
  607. else:
  608. self._downloader.report_warning(u'Unable to extract video title')
  609. video_title = u'_'
  610. # thumbnail image
  611. # We try first to get a high quality image:
  612. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  613. video_webpage, re.DOTALL)
  614. if m_thumb is not None:
  615. video_thumbnail = m_thumb.group(1)
  616. elif 'thumbnail_url' not in video_info:
  617. self._downloader.report_warning(u'unable to extract video thumbnail')
  618. video_thumbnail = None
  619. else: # don't panic if we can't find it
  620. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  621. # upload date
  622. upload_date = None
  623. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  624. if mobj is None:
  625. mobj = re.search(
  626. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  627. video_webpage)
  628. if mobj is not None:
  629. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  630. upload_date = unified_strdate(upload_date)
  631. m_cat_container = get_element_by_id("eow-category", video_webpage)
  632. if m_cat_container:
  633. category = self._html_search_regex(
  634. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  635. default=None)
  636. video_categories = None if category is None else [category]
  637. else:
  638. video_categories = None
  639. # description
  640. video_description = get_element_by_id("eow-description", video_webpage)
  641. if video_description:
  642. video_description = re.sub(r'''(?x)
  643. <a\s+
  644. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  645. title="([^"]+)"\s+
  646. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  647. class="yt-uix-redirect-link"\s*>
  648. [^<]+
  649. </a>
  650. ''', r'\1', video_description)
  651. video_description = clean_html(video_description)
  652. else:
  653. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  654. if fd_mobj:
  655. video_description = unescapeHTML(fd_mobj.group(1))
  656. else:
  657. video_description = u''
  658. def _extract_count(klass):
  659. count = self._search_regex(
  660. r'class="%s">([\d,]+)</span>' % re.escape(klass),
  661. video_webpage, klass, default=None)
  662. if count is not None:
  663. return int(count.replace(',', ''))
  664. return None
  665. like_count = _extract_count(u'likes-count')
  666. dislike_count = _extract_count(u'dislikes-count')
  667. # subtitles
  668. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  669. if self._downloader.params.get('listsubtitles', False):
  670. self._list_available_subtitles(video_id, video_webpage)
  671. return
  672. if 'length_seconds' not in video_info:
  673. self._downloader.report_warning(u'unable to extract video duration')
  674. video_duration = None
  675. else:
  676. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  677. # annotations
  678. video_annotations = None
  679. if self._downloader.params.get('writeannotations', False):
  680. video_annotations = self._extract_annotations(video_id)
  681. # Decide which formats to download
  682. try:
  683. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  684. if not mobj:
  685. raise ValueError('Could not find vevo ID')
  686. json_code = uppercase_escape(mobj.group(1))
  687. ytplayer_config = json.loads(json_code)
  688. args = ytplayer_config['args']
  689. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  690. # this signatures are encrypted
  691. if 'url_encoded_fmt_stream_map' not in args:
  692. raise ValueError(u'No stream_map present') # caught below
  693. re_signature = re.compile(r'[&,]s=')
  694. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  695. if m_s is not None:
  696. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  697. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  698. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  699. if m_s is not None:
  700. if 'adaptive_fmts' in video_info:
  701. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  702. else:
  703. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  704. except ValueError:
  705. pass
  706. def _map_to_format_list(urlmap):
  707. formats = []
  708. for itag, video_real_url in urlmap.items():
  709. dct = {
  710. 'format_id': itag,
  711. 'url': video_real_url,
  712. 'player_url': player_url,
  713. }
  714. if itag in self._formats:
  715. dct.update(self._formats[itag])
  716. formats.append(dct)
  717. return formats
  718. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  719. self.report_rtmp_download()
  720. formats = [{
  721. 'format_id': '_rtmp',
  722. 'protocol': 'rtmp',
  723. 'url': video_info['conn'][0],
  724. 'player_url': player_url,
  725. }]
  726. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  727. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  728. if 'rtmpe%3Dyes' in encoded_url_map:
  729. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  730. url_map = {}
  731. for url_data_str in encoded_url_map.split(','):
  732. url_data = compat_parse_qs(url_data_str)
  733. if 'itag' in url_data and 'url' in url_data:
  734. url = url_data['url'][0]
  735. if 'sig' in url_data:
  736. url += '&signature=' + url_data['sig'][0]
  737. elif 's' in url_data:
  738. encrypted_sig = url_data['s'][0]
  739. if not age_gate:
  740. jsplayer_url_json = self._search_regex(
  741. r'"assets":.+?"js":\s*("[^"]+")',
  742. video_webpage, u'JS player URL')
  743. player_url = json.loads(jsplayer_url_json)
  744. if player_url is None:
  745. player_url_json = self._search_regex(
  746. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  747. video_webpage, u'age gate player URL')
  748. player_url = json.loads(player_url_json)
  749. if self._downloader.params.get('verbose'):
  750. if player_url is None:
  751. player_version = 'unknown'
  752. player_desc = 'unknown'
  753. else:
  754. if player_url.endswith('swf'):
  755. player_version = self._search_regex(
  756. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  757. u'flash player', fatal=False)
  758. player_desc = 'flash player %s' % player_version
  759. else:
  760. player_version = self._search_regex(
  761. r'html5player-(.+?)\.js', video_webpage,
  762. 'html5 player', fatal=False)
  763. player_desc = u'html5 player %s' % player_version
  764. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  765. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  766. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  767. signature = self._decrypt_signature(
  768. encrypted_sig, video_id, player_url, age_gate)
  769. url += '&signature=' + signature
  770. if 'ratebypass' not in url:
  771. url += '&ratebypass=yes'
  772. url_map[url_data['itag'][0]] = url
  773. formats = _map_to_format_list(url_map)
  774. elif video_info.get('hlsvp'):
  775. manifest_url = video_info['hlsvp'][0]
  776. url_map = self._extract_from_m3u8(manifest_url, video_id)
  777. formats = _map_to_format_list(url_map)
  778. else:
  779. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  780. # Look for the DASH manifest
  781. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  782. try:
  783. # The DASH manifest used needs to be the one from the original video_webpage.
  784. # The one found in get_video_info seems to be using different signatures.
  785. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  786. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  787. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  788. if age_gate:
  789. dash_manifest_url = video_info.get('dashmpd')[0]
  790. else:
  791. dash_manifest_url = ytplayer_config['args']['dashmpd']
  792. def decrypt_sig(mobj):
  793. s = mobj.group(1)
  794. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  795. return '/signature/%s' % dec_s
  796. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  797. dash_doc = self._download_xml(
  798. dash_manifest_url, video_id,
  799. note=u'Downloading DASH manifest',
  800. errnote=u'Could not download DASH manifest')
  801. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  802. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  803. if url_el is None:
  804. continue
  805. format_id = r.attrib['id']
  806. video_url = url_el.text
  807. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  808. f = {
  809. 'format_id': format_id,
  810. 'url': video_url,
  811. 'width': int_or_none(r.attrib.get('width')),
  812. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  813. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  814. 'filesize': filesize,
  815. }
  816. try:
  817. existing_format = next(
  818. fo for fo in formats
  819. if fo['format_id'] == format_id)
  820. except StopIteration:
  821. f.update(self._formats.get(format_id, {}))
  822. formats.append(f)
  823. else:
  824. existing_format.update(f)
  825. except (ExtractorError, KeyError) as e:
  826. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  827. self._sort_formats(formats)
  828. return {
  829. 'id': video_id,
  830. 'uploader': video_uploader,
  831. 'uploader_id': video_uploader_id,
  832. 'upload_date': upload_date,
  833. 'title': video_title,
  834. 'thumbnail': video_thumbnail,
  835. 'description': video_description,
  836. 'categories': video_categories,
  837. 'subtitles': video_subtitles,
  838. 'duration': video_duration,
  839. 'age_limit': 18 if age_gate else 0,
  840. 'annotations': video_annotations,
  841. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  842. 'view_count': view_count,
  843. 'like_count': like_count,
  844. 'dislike_count': dislike_count,
  845. 'formats': formats,
  846. }
  847. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  848. IE_DESC = u'YouTube.com playlists'
  849. _VALID_URL = r"""(?x)(?:
  850. (?:https?://)?
  851. (?:\w+\.)?
  852. youtube\.com/
  853. (?:
  854. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  855. \? (?:.*?&)*? (?:p|a|list)=
  856. | p/
  857. )
  858. (
  859. (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  860. # Top tracks, they can also include dots
  861. |(?:MC)[\w\.]*
  862. )
  863. .*
  864. |
  865. ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  866. )"""
  867. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  868. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  869. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  870. IE_NAME = u'youtube:playlist'
  871. def _real_initialize(self):
  872. self._login()
  873. def _ids_to_results(self, ids):
  874. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  875. for vid_id in ids]
  876. def _extract_mix(self, playlist_id):
  877. # The mixes are generated from a a single video
  878. # the id of the playlist is just 'RD' + video_id
  879. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  880. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  881. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  882. title_span = (search_title('playlist-title') or
  883. search_title('title long-title') or search_title('title'))
  884. title = clean_html(title_span)
  885. video_re = r'''(?x)data-video-username=".*?".*?
  886. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id)
  887. ids = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
  888. url_results = self._ids_to_results(ids)
  889. return self.playlist_result(url_results, playlist_id, title)
  890. def _real_extract(self, url):
  891. # Extract playlist id
  892. mobj = re.match(self._VALID_URL, url)
  893. if mobj is None:
  894. raise ExtractorError(u'Invalid URL: %s' % url)
  895. playlist_id = mobj.group(1) or mobj.group(2)
  896. # Check if it's a video-specific URL
  897. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  898. if 'v' in query_dict:
  899. video_id = query_dict['v'][0]
  900. if self._downloader.params.get('noplaylist'):
  901. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  902. return self.url_result(video_id, 'Youtube', video_id=video_id)
  903. else:
  904. self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  905. if playlist_id.startswith('RD'):
  906. # Mixes require a custom extraction process
  907. return self._extract_mix(playlist_id)
  908. if playlist_id.startswith('TL'):
  909. raise ExtractorError(u'For downloading YouTube.com top lists, use '
  910. u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  911. url = self._TEMPLATE_URL % playlist_id
  912. page = self._download_webpage(url, playlist_id)
  913. more_widget_html = content_html = page
  914. # Check if the playlist exists or is private
  915. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  916. raise ExtractorError(
  917. u'The playlist doesn\'t exist or is private, use --username or '
  918. '--netrc to access it.',
  919. expected=True)
  920. # Extract the video ids from the playlist pages
  921. ids = []
  922. for page_num in itertools.count(1):
  923. matches = re.finditer(self._VIDEO_RE, content_html)
  924. # We remove the duplicates and the link with index 0
  925. # (it's not the first video of the playlist)
  926. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  927. ids.extend(new_ids)
  928. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  929. if not mobj:
  930. break
  931. more = self._download_json(
  932. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  933. 'Downloading page #%s' % page_num,
  934. transform_source=uppercase_escape)
  935. content_html = more['content_html']
  936. more_widget_html = more['load_more_widget_html']
  937. playlist_title = self._html_search_regex(
  938. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  939. page, u'title')
  940. url_results = self._ids_to_results(ids)
  941. return self.playlist_result(url_results, playlist_id, playlist_title)
  942. class YoutubeTopListIE(YoutubePlaylistIE):
  943. IE_NAME = u'youtube:toplist'
  944. IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  945. u' (Example: "yttoplist:music:Top Tracks")')
  946. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  947. def _real_extract(self, url):
  948. mobj = re.match(self._VALID_URL, url)
  949. channel = mobj.group('chann')
  950. title = mobj.group('title')
  951. query = compat_urllib_parse.urlencode({'title': title})
  952. playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
  953. channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
  954. link = self._html_search_regex(playlist_re, channel_page, u'list')
  955. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  956. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  957. ids = []
  958. # sometimes the webpage doesn't contain the videos
  959. # retry until we get them
  960. for i in itertools.count(0):
  961. msg = u'Downloading Youtube mix'
  962. if i > 0:
  963. msg += ', retry #%d' % i
  964. webpage = self._download_webpage(url, title, msg)
  965. ids = orderedSet(re.findall(video_re, webpage))
  966. if ids:
  967. break
  968. url_results = self._ids_to_results(ids)
  969. return self.playlist_result(url_results, playlist_title=title)
  970. class YoutubeChannelIE(InfoExtractor):
  971. IE_DESC = u'YouTube.com channels'
  972. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  973. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  974. _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'
  975. IE_NAME = u'youtube:channel'
  976. def extract_videos_from_page(self, page):
  977. ids_in_page = []
  978. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  979. if mobj.group(1) not in ids_in_page:
  980. ids_in_page.append(mobj.group(1))
  981. return ids_in_page
  982. def _real_extract(self, url):
  983. # Extract channel id
  984. mobj = re.match(self._VALID_URL, url)
  985. if mobj is None:
  986. raise ExtractorError(u'Invalid URL: %s' % url)
  987. # Download channel page
  988. channel_id = mobj.group(1)
  989. video_ids = []
  990. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  991. channel_page = self._download_webpage(url, channel_id)
  992. autogenerated = re.search(r'''(?x)
  993. class="[^"]*?(?:
  994. channel-header-autogenerated-label|
  995. yt-channel-title-autogenerated
  996. )[^"]*"''', channel_page) is not None
  997. if autogenerated:
  998. # The videos are contained in a single page
  999. # the ajax pages can't be used, they are empty
  1000. video_ids = self.extract_videos_from_page(channel_page)
  1001. else:
  1002. # Download all channel pages using the json-based channel_ajax query
  1003. for pagenum in itertools.count(1):
  1004. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1005. page = self._download_json(
  1006. url, channel_id, note=u'Downloading page #%s' % pagenum,
  1007. transform_source=uppercase_escape)
  1008. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1009. video_ids.extend(ids_in_page)
  1010. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1011. break
  1012. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1013. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1014. for video_id in video_ids]
  1015. return self.playlist_result(url_entries, channel_id)
  1016. class YoutubeUserIE(InfoExtractor):
  1017. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1018. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1019. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1020. _GDATA_PAGE_SIZE = 50
  1021. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1022. IE_NAME = u'youtube:user'
  1023. @classmethod
  1024. def suitable(cls, url):
  1025. # Don't return True if the url can be extracted with other youtube
  1026. # extractor, the regex would is too permissive and it would match.
  1027. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1028. if any(ie.suitable(url) for ie in other_ies): return False
  1029. else: return super(YoutubeUserIE, cls).suitable(url)
  1030. def _real_extract(self, url):
  1031. # Extract username
  1032. mobj = re.match(self._VALID_URL, url)
  1033. if mobj is None:
  1034. raise ExtractorError(u'Invalid URL: %s' % url)
  1035. username = mobj.group(1)
  1036. # Download video ids using YouTube Data API. Result size per
  1037. # query is limited (currently to 50 videos) so we need to query
  1038. # page by page until there are no video ids - it means we got
  1039. # all of them.
  1040. def download_page(pagenum):
  1041. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1042. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1043. page = self._download_webpage(
  1044. gdata_url, username,
  1045. u'Downloading video ids from %d to %d' % (
  1046. start_index, start_index + self._GDATA_PAGE_SIZE))
  1047. try:
  1048. response = json.loads(page)
  1049. except ValueError as err:
  1050. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1051. if 'entry' not in response['feed']:
  1052. return
  1053. # Extract video identifiers
  1054. entries = response['feed']['entry']
  1055. for entry in entries:
  1056. title = entry['title']['$t']
  1057. video_id = entry['id']['$t'].split('/')[-1]
  1058. yield {
  1059. '_type': 'url',
  1060. 'url': video_id,
  1061. 'ie_key': 'Youtube',
  1062. 'id': video_id,
  1063. 'title': title,
  1064. }
  1065. url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
  1066. return self.playlist_result(url_results, playlist_title=username)
  1067. class YoutubeSearchIE(SearchInfoExtractor):
  1068. IE_DESC = u'YouTube.com searches'
  1069. _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1070. _MAX_RESULTS = 1000
  1071. IE_NAME = u'youtube:search'
  1072. _SEARCH_KEY = 'ytsearch'
  1073. def _get_n_results(self, query, n):
  1074. """Get a specified number of results for a query"""
  1075. video_ids = []
  1076. pagenum = 0
  1077. limit = n
  1078. PAGE_SIZE = 50
  1079. while (PAGE_SIZE * pagenum) < limit:
  1080. result_url = self._API_URL % (
  1081. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1082. (PAGE_SIZE * pagenum) + 1)
  1083. data_json = self._download_webpage(
  1084. result_url, video_id=u'query "%s"' % query,
  1085. note=u'Downloading page %s' % (pagenum + 1),
  1086. errnote=u'Unable to download API page')
  1087. data = json.loads(data_json)
  1088. api_response = data['data']
  1089. if 'items' not in api_response:
  1090. raise ExtractorError(
  1091. u'[youtube] No video results', expected=True)
  1092. new_ids = list(video['id'] for video in api_response['items'])
  1093. video_ids += new_ids
  1094. limit = min(n, api_response['totalItems'])
  1095. pagenum += 1
  1096. if len(video_ids) > n:
  1097. video_ids = video_ids[:n]
  1098. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1099. for video_id in video_ids]
  1100. return self.playlist_result(videos, query)
  1101. class YoutubeSearchDateIE(YoutubeSearchIE):
  1102. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1103. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1104. _SEARCH_KEY = 'ytsearchdate'
  1105. IE_DESC = u'YouTube.com searches, newest videos first'
  1106. class YoutubeSearchURLIE(InfoExtractor):
  1107. IE_DESC = u'YouTube.com search URLs'
  1108. IE_NAME = u'youtube:search_url'
  1109. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1110. def _real_extract(self, url):
  1111. mobj = re.match(self._VALID_URL, url)
  1112. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1113. webpage = self._download_webpage(url, query)
  1114. result_code = self._search_regex(
  1115. r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
  1116. part_codes = re.findall(
  1117. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1118. entries = []
  1119. for part_code in part_codes:
  1120. part_title = self._html_search_regex(
  1121. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1122. part_url_snippet = self._html_search_regex(
  1123. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1124. part_url = compat_urlparse.urljoin(
  1125. 'https://www.youtube.com/', part_url_snippet)
  1126. entries.append({
  1127. '_type': 'url',
  1128. 'url': part_url,
  1129. 'title': part_title,
  1130. })
  1131. return {
  1132. '_type': 'playlist',
  1133. 'entries': entries,
  1134. 'title': query,
  1135. }
  1136. class YoutubeShowIE(InfoExtractor):
  1137. IE_DESC = u'YouTube.com (multi-season) shows'
  1138. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1139. IE_NAME = u'youtube:show'
  1140. def _real_extract(self, url):
  1141. mobj = re.match(self._VALID_URL, url)
  1142. show_name = mobj.group(1)
  1143. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1144. # There's one playlist for each season of the show
  1145. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1146. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1147. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1148. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1149. """
  1150. Base class for extractors that fetch info from
  1151. http://www.youtube.com/feed_ajax
  1152. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1153. """
  1154. _LOGIN_REQUIRED = True
  1155. # use action_load_personal_feed instead of action_load_system_feed
  1156. _PERSONAL_FEED = False
  1157. @property
  1158. def _FEED_TEMPLATE(self):
  1159. action = 'action_load_system_feed'
  1160. if self._PERSONAL_FEED:
  1161. action = 'action_load_personal_feed'
  1162. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1163. @property
  1164. def IE_NAME(self):
  1165. return u'youtube:%s' % self._FEED_NAME
  1166. def _real_initialize(self):
  1167. self._login()
  1168. def _real_extract(self, url):
  1169. feed_entries = []
  1170. paging = 0
  1171. for i in itertools.count(1):
  1172. info = self._download_json(self._FEED_TEMPLATE % paging,
  1173. u'%s feed' % self._FEED_NAME,
  1174. u'Downloading page %s' % i)
  1175. feed_html = info.get('feed_html') or info.get('content_html')
  1176. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1177. ids = orderedSet(m.group(1) for m in m_ids)
  1178. feed_entries.extend(
  1179. self.url_result(video_id, 'Youtube', video_id=video_id)
  1180. for video_id in ids)
  1181. mobj = re.search(
  1182. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1183. feed_html)
  1184. if mobj is None:
  1185. break
  1186. paging = mobj.group('paging')
  1187. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1188. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1189. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1190. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1191. _FEED_NAME = 'subscriptions'
  1192. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1193. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1194. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1195. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1196. _FEED_NAME = 'recommended'
  1197. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1198. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1199. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1200. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1201. _FEED_NAME = 'watch_later'
  1202. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1203. _PERSONAL_FEED = True
  1204. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1205. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1206. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1207. _FEED_NAME = 'history'
  1208. _PERSONAL_FEED = True
  1209. _PLAYLIST_TITLE = u'Youtube Watch History'
  1210. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1211. IE_NAME = u'youtube:favorites'
  1212. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1213. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1214. _LOGIN_REQUIRED = True
  1215. def _real_extract(self, url):
  1216. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1217. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1218. return self.url_result(playlist_id, 'YoutubePlaylist')
  1219. class YoutubeTruncatedURLIE(InfoExtractor):
  1220. IE_NAME = 'youtube:truncated_url'
  1221. IE_DESC = False # Do not list
  1222. _VALID_URL = r'''(?x)
  1223. (?:https?://)?[^/]+/watch\?(?:
  1224. feature=[a-z_]+|
  1225. annotation_id=annotation_[^&]+
  1226. )?$|
  1227. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1228. '''
  1229. _TESTS = [{
  1230. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1231. 'only_matching': True,
  1232. }, {
  1233. 'url': 'http://www.youtube.com/watch?',
  1234. 'only_matching': True,
  1235. }]
  1236. def _real_extract(self, url):
  1237. raise ExtractorError(
  1238. u'Did you forget to quote the URL? Remember that & is a meta '
  1239. u'character in most shells, so you want to put the URL in quotes, '
  1240. u'like youtube-dl '
  1241. u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1242. u' or simply youtube-dl BaW_jenozKc .',
  1243. expected=True)