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.

1401 lines
63 KiB

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