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.

1423 lines
64 KiB

12 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 _signature_cache_id(self, example_sig):
  316. """ Return a string representation of a signature """
  317. return u'.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  318. def _extract_signature_function(self, video_id, player_url, example_sig):
  319. id_m = re.match(
  320. r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
  321. player_url)
  322. if not id_m:
  323. raise ExtractorError('Cannot identify player %r' % player_url)
  324. player_type = id_m.group('ext')
  325. player_id = id_m.group('id')
  326. # Read from filesystem cache
  327. func_id = '%s_%s_%s' % (
  328. player_type, player_id, self._signature_cache_id(example_sig))
  329. assert os.path.basename(func_id) == func_id
  330. cache_dir = get_cachedir(self._downloader.params)
  331. cache_enabled = cache_dir is not None
  332. if cache_enabled:
  333. cache_fn = os.path.join(os.path.expanduser(cache_dir),
  334. u'youtube-sigfuncs',
  335. func_id + '.json')
  336. try:
  337. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  338. cache_spec = json.load(cachef)
  339. return lambda s: u''.join(s[i] for i in cache_spec)
  340. except IOError:
  341. pass # No cache available
  342. except ValueError:
  343. try:
  344. file_size = os.path.getsize(cache_fn)
  345. except (OSError, IOError) as oe:
  346. file_size = str(oe)
  347. self._downloader.report_warning(
  348. u'Cache %s failed (%s)' % (cache_fn, file_size))
  349. if player_type == 'js':
  350. code = self._download_webpage(
  351. player_url, video_id,
  352. note=u'Downloading %s player %s' % (player_type, player_id),
  353. errnote=u'Download of %s failed' % player_url)
  354. res = self._parse_sig_js(code)
  355. elif player_type == 'swf':
  356. urlh = self._request_webpage(
  357. player_url, video_id,
  358. note=u'Downloading %s player %s' % (player_type, player_id),
  359. errnote=u'Download of %s failed' % player_url)
  360. code = urlh.read()
  361. res = self._parse_sig_swf(code)
  362. else:
  363. assert False, 'Invalid player type %r' % player_type
  364. if cache_enabled:
  365. try:
  366. test_string = u''.join(map(compat_chr, range(len(example_sig))))
  367. cache_res = res(test_string)
  368. cache_spec = [ord(c) for c in cache_res]
  369. try:
  370. os.makedirs(os.path.dirname(cache_fn))
  371. except OSError as ose:
  372. if ose.errno != errno.EEXIST:
  373. raise
  374. write_json_file(cache_spec, cache_fn)
  375. except Exception:
  376. tb = traceback.format_exc()
  377. self._downloader.report_warning(
  378. u'Writing cache to %r failed: %s' % (cache_fn, tb))
  379. return res
  380. def _print_sig_code(self, func, example_sig):
  381. def gen_sig_code(idxs):
  382. def _genslice(start, end, step):
  383. starts = u'' if start == 0 else str(start)
  384. ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
  385. steps = u'' if step == 1 else (u':%d' % step)
  386. return u's[%s%s%s]' % (starts, ends, steps)
  387. step = None
  388. start = '(Never used)' # Quelch pyflakes warnings - start will be
  389. # set as soon as step is set
  390. for i, prev in zip(idxs[1:], idxs[:-1]):
  391. if step is not None:
  392. if i - prev == step:
  393. continue
  394. yield _genslice(start, prev, step)
  395. step = None
  396. continue
  397. if i - prev in [-1, 1]:
  398. step = i - prev
  399. start = prev
  400. continue
  401. else:
  402. yield u's[%d]' % prev
  403. if step is None:
  404. yield u's[%d]' % i
  405. else:
  406. yield _genslice(start, i, step)
  407. test_string = u''.join(map(compat_chr, range(len(example_sig))))
  408. cache_res = func(test_string)
  409. cache_spec = [ord(c) for c in cache_res]
  410. expr_code = u' + '.join(gen_sig_code(cache_spec))
  411. signature_id_tuple = '(%s)' % (
  412. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  413. code = (u'if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  414. u' return %s\n') % (signature_id_tuple, expr_code)
  415. self.to_screen(u'Extracted signature function:\n' + code)
  416. def _parse_sig_js(self, jscode):
  417. funcname = self._search_regex(
  418. r'signature=([$a-zA-Z]+)', jscode,
  419. u'Initial JS player signature function name')
  420. jsi = JSInterpreter(jscode)
  421. initial_function = jsi.extract_function(funcname)
  422. return lambda s: initial_function([s])
  423. def _parse_sig_swf(self, file_contents):
  424. swfi = SWFInterpreter(file_contents)
  425. TARGET_CLASSNAME = u'SignatureDecipher'
  426. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  427. initial_function = swfi.extract_function(searched_class, u'decipher')
  428. return lambda s: initial_function([s])
  429. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  430. """Turn the encrypted s field into a working signature"""
  431. if player_url is None:
  432. raise ExtractorError(u'Cannot decrypt signature without player_url')
  433. if player_url.startswith(u'//'):
  434. player_url = u'https:' + player_url
  435. try:
  436. player_id = (player_url, self._signature_cache_id(s))
  437. if player_id not in self._player_cache:
  438. func = self._extract_signature_function(
  439. video_id, player_url, s
  440. )
  441. self._player_cache[player_id] = func
  442. func = self._player_cache[player_id]
  443. if self._downloader.params.get('youtube_print_sig_code'):
  444. self._print_sig_code(func, s)
  445. return func(s)
  446. except Exception as e:
  447. tb = traceback.format_exc()
  448. raise ExtractorError(
  449. u'Signature extraction failed: ' + tb, cause=e)
  450. def _get_available_subtitles(self, video_id, webpage):
  451. try:
  452. sub_list = self._download_webpage(
  453. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  454. video_id, note=False)
  455. except ExtractorError as err:
  456. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  457. return {}
  458. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  459. sub_lang_list = {}
  460. for l in lang_list:
  461. lang = l[1]
  462. params = compat_urllib_parse.urlencode({
  463. 'lang': lang,
  464. 'v': video_id,
  465. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  466. 'name': unescapeHTML(l[0]).encode('utf-8'),
  467. })
  468. url = u'https://www.youtube.com/api/timedtext?' + params
  469. sub_lang_list[lang] = url
  470. if not sub_lang_list:
  471. self._downloader.report_warning(u'video doesn\'t have subtitles')
  472. return {}
  473. return sub_lang_list
  474. def _get_available_automatic_caption(self, video_id, webpage):
  475. """We need the webpage for getting the captions url, pass it as an
  476. argument to speed up the process."""
  477. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  478. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  479. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  480. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  481. if mobj is None:
  482. self._downloader.report_warning(err_msg)
  483. return {}
  484. player_config = json.loads(mobj.group(1))
  485. try:
  486. args = player_config[u'args']
  487. caption_url = args[u'ttsurl']
  488. timestamp = args[u'timestamp']
  489. # We get the available subtitles
  490. list_params = compat_urllib_parse.urlencode({
  491. 'type': 'list',
  492. 'tlangs': 1,
  493. 'asrs': 1,
  494. })
  495. list_url = caption_url + '&' + list_params
  496. caption_list = self._download_xml(list_url, video_id)
  497. original_lang_node = caption_list.find('track')
  498. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  499. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  500. return {}
  501. original_lang = original_lang_node.attrib['lang_code']
  502. sub_lang_list = {}
  503. for lang_node in caption_list.findall('target'):
  504. sub_lang = lang_node.attrib['lang_code']
  505. params = compat_urllib_parse.urlencode({
  506. 'lang': original_lang,
  507. 'tlang': sub_lang,
  508. 'fmt': sub_format,
  509. 'ts': timestamp,
  510. 'kind': 'asr',
  511. })
  512. sub_lang_list[sub_lang] = caption_url + '&' + params
  513. return sub_lang_list
  514. # An extractor error can be raise by the download process if there are
  515. # no automatic captions but there are subtitles
  516. except (KeyError, ExtractorError):
  517. self._downloader.report_warning(err_msg)
  518. return {}
  519. @classmethod
  520. def extract_id(cls, url):
  521. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  522. if mobj is None:
  523. raise ExtractorError(u'Invalid URL: %s' % url)
  524. video_id = mobj.group(2)
  525. return video_id
  526. def _extract_from_m3u8(self, manifest_url, video_id):
  527. url_map = {}
  528. def _get_urls(_manifest):
  529. lines = _manifest.split('\n')
  530. urls = filter(lambda l: l and not l.startswith('#'),
  531. lines)
  532. return urls
  533. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  534. formats_urls = _get_urls(manifest)
  535. for format_url in formats_urls:
  536. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  537. url_map[itag] = format_url
  538. return url_map
  539. def _extract_annotations(self, video_id):
  540. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  541. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  542. def _real_extract(self, url):
  543. proto = (
  544. u'http' if self._downloader.params.get('prefer_insecure', False)
  545. else u'https')
  546. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  547. mobj = re.search(self._NEXT_URL_RE, url)
  548. if mobj:
  549. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  550. video_id = self.extract_id(url)
  551. # Get video webpage
  552. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  553. video_webpage = self._download_webpage(url, video_id)
  554. # Attempt to extract SWF player URL
  555. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  556. if mobj is not None:
  557. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  558. else:
  559. player_url = None
  560. # Get video info
  561. self.report_video_info_webpage_download(video_id)
  562. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  563. self.report_age_confirmation()
  564. age_gate = True
  565. # We simulate the access to the video from www.youtube.com/v/{video_id}
  566. # this can be viewed without login into Youtube
  567. data = compat_urllib_parse.urlencode({
  568. 'video_id': video_id,
  569. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  570. 'sts': self._search_regex(
  571. r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
  572. })
  573. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  574. video_info_webpage = self._download_webpage(video_info_url, video_id,
  575. note=False,
  576. errnote='unable to download video info webpage')
  577. video_info = compat_parse_qs(video_info_webpage)
  578. else:
  579. age_gate = False
  580. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  581. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  582. % (video_id, el_type))
  583. video_info_webpage = self._download_webpage(video_info_url, video_id,
  584. note=False,
  585. errnote='unable to download video info webpage')
  586. video_info = compat_parse_qs(video_info_webpage)
  587. if 'token' in video_info:
  588. break
  589. if 'token' not in video_info:
  590. if 'reason' in video_info:
  591. raise ExtractorError(
  592. u'YouTube said: %s' % video_info['reason'][0],
  593. expected=True, video_id=video_id)
  594. else:
  595. raise ExtractorError(
  596. u'"token" parameter not in video info for unknown reason',
  597. video_id=video_id)
  598. if 'view_count' in video_info:
  599. view_count = int(video_info['view_count'][0])
  600. else:
  601. view_count = None
  602. # Check for "rental" videos
  603. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  604. raise ExtractorError(u'"rental" videos not supported')
  605. # Start extracting information
  606. self.report_information_extraction(video_id)
  607. # uploader
  608. if 'author' not in video_info:
  609. raise ExtractorError(u'Unable to extract uploader name')
  610. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  611. # uploader_id
  612. video_uploader_id = None
  613. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  614. if mobj is not None:
  615. video_uploader_id = mobj.group(1)
  616. else:
  617. self._downloader.report_warning(u'unable to extract uploader nickname')
  618. # title
  619. if 'title' in video_info:
  620. video_title = video_info['title'][0]
  621. else:
  622. self._downloader.report_warning(u'Unable to extract video title')
  623. video_title = u'_'
  624. # thumbnail image
  625. # We try first to get a high quality image:
  626. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  627. video_webpage, re.DOTALL)
  628. if m_thumb is not None:
  629. video_thumbnail = m_thumb.group(1)
  630. elif 'thumbnail_url' not in video_info:
  631. self._downloader.report_warning(u'unable to extract video thumbnail')
  632. video_thumbnail = None
  633. else: # don't panic if we can't find it
  634. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  635. # upload date
  636. upload_date = None
  637. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  638. if mobj is None:
  639. mobj = re.search(
  640. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  641. video_webpage)
  642. if mobj is not None:
  643. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  644. upload_date = unified_strdate(upload_date)
  645. m_cat_container = get_element_by_id("eow-category", video_webpage)
  646. if m_cat_container:
  647. category = self._html_search_regex(
  648. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  649. default=None)
  650. video_categories = None if category is None else [category]
  651. else:
  652. video_categories = None
  653. # description
  654. video_description = get_element_by_id("eow-description", video_webpage)
  655. if video_description:
  656. video_description = re.sub(r'''(?x)
  657. <a\s+
  658. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  659. title="([^"]+)"\s+
  660. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  661. class="yt-uix-redirect-link"\s*>
  662. [^<]+
  663. </a>
  664. ''', r'\1', video_description)
  665. video_description = clean_html(video_description)
  666. else:
  667. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  668. if fd_mobj:
  669. video_description = unescapeHTML(fd_mobj.group(1))
  670. else:
  671. video_description = u''
  672. def _extract_count(klass):
  673. count = self._search_regex(
  674. r'class="%s">([\d,]+)</span>' % re.escape(klass),
  675. video_webpage, klass, default=None)
  676. if count is not None:
  677. return int(count.replace(',', ''))
  678. return None
  679. like_count = _extract_count(u'likes-count')
  680. dislike_count = _extract_count(u'dislikes-count')
  681. # subtitles
  682. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  683. if self._downloader.params.get('listsubtitles', False):
  684. self._list_available_subtitles(video_id, video_webpage)
  685. return
  686. if 'length_seconds' not in video_info:
  687. self._downloader.report_warning(u'unable to extract video duration')
  688. video_duration = None
  689. else:
  690. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  691. # annotations
  692. video_annotations = None
  693. if self._downloader.params.get('writeannotations', False):
  694. video_annotations = self._extract_annotations(video_id)
  695. # Decide which formats to download
  696. try:
  697. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  698. if not mobj:
  699. raise ValueError('Could not find vevo ID')
  700. json_code = uppercase_escape(mobj.group(1))
  701. ytplayer_config = json.loads(json_code)
  702. args = ytplayer_config['args']
  703. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  704. # this signatures are encrypted
  705. if 'url_encoded_fmt_stream_map' not in args:
  706. raise ValueError(u'No stream_map present') # caught below
  707. re_signature = re.compile(r'[&,]s=')
  708. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  709. if m_s is not None:
  710. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  711. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  712. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  713. if m_s is not None:
  714. if 'adaptive_fmts' in video_info:
  715. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  716. else:
  717. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  718. except ValueError:
  719. pass
  720. def _map_to_format_list(urlmap):
  721. formats = []
  722. for itag, video_real_url in urlmap.items():
  723. dct = {
  724. 'format_id': itag,
  725. 'url': video_real_url,
  726. 'player_url': player_url,
  727. }
  728. if itag in self._formats:
  729. dct.update(self._formats[itag])
  730. formats.append(dct)
  731. return formats
  732. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  733. self.report_rtmp_download()
  734. formats = [{
  735. 'format_id': '_rtmp',
  736. 'protocol': 'rtmp',
  737. 'url': video_info['conn'][0],
  738. 'player_url': player_url,
  739. }]
  740. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  741. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  742. if 'rtmpe%3Dyes' in encoded_url_map:
  743. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  744. url_map = {}
  745. for url_data_str in encoded_url_map.split(','):
  746. url_data = compat_parse_qs(url_data_str)
  747. if 'itag' not in url_data or 'url' not in url_data:
  748. continue
  749. format_id = url_data['itag'][0]
  750. url = url_data['url'][0]
  751. if 'sig' in url_data:
  752. url += '&signature=' + url_data['sig'][0]
  753. elif 's' in url_data:
  754. encrypted_sig = url_data['s'][0]
  755. if not age_gate:
  756. jsplayer_url_json = self._search_regex(
  757. r'"assets":.+?"js":\s*("[^"]+")',
  758. video_webpage, u'JS player URL')
  759. player_url = json.loads(jsplayer_url_json)
  760. if player_url is None:
  761. player_url_json = self._search_regex(
  762. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  763. video_webpage, u'age gate player URL')
  764. player_url = json.loads(player_url_json)
  765. if self._downloader.params.get('verbose'):
  766. if player_url is None:
  767. player_version = 'unknown'
  768. player_desc = 'unknown'
  769. else:
  770. if player_url.endswith('swf'):
  771. player_version = self._search_regex(
  772. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  773. u'flash player', fatal=False)
  774. player_desc = 'flash player %s' % player_version
  775. else:
  776. player_version = self._search_regex(
  777. r'html5player-([^/]+?)(?:/html5player)?\.js',
  778. player_url,
  779. 'html5 player', fatal=False)
  780. player_desc = u'html5 player %s' % player_version
  781. parts_sizes = self._signature_cache_id(encrypted_sig)
  782. self.to_screen(u'{%s} signature length %s, %s' %
  783. (format_id, parts_sizes, player_desc))
  784. signature = self._decrypt_signature(
  785. encrypted_sig, video_id, player_url, age_gate)
  786. url += '&signature=' + signature
  787. if 'ratebypass' not in url:
  788. url += '&ratebypass=yes'
  789. url_map[format_id] = url
  790. formats = _map_to_format_list(url_map)
  791. elif video_info.get('hlsvp'):
  792. manifest_url = video_info['hlsvp'][0]
  793. url_map = self._extract_from_m3u8(manifest_url, video_id)
  794. formats = _map_to_format_list(url_map)
  795. else:
  796. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  797. # Look for the DASH manifest
  798. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  799. try:
  800. # The DASH manifest used needs to be the one from the original video_webpage.
  801. # The one found in get_video_info seems to be using different signatures.
  802. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  803. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  804. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  805. if age_gate:
  806. dash_manifest_url = video_info.get('dashmpd')[0]
  807. else:
  808. dash_manifest_url = ytplayer_config['args']['dashmpd']
  809. def decrypt_sig(mobj):
  810. s = mobj.group(1)
  811. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  812. return '/signature/%s' % dec_s
  813. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  814. dash_doc = self._download_xml(
  815. dash_manifest_url, video_id,
  816. note=u'Downloading DASH manifest',
  817. errnote=u'Could not download DASH manifest')
  818. for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  819. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  820. if url_el is None:
  821. continue
  822. format_id = r.attrib['id']
  823. video_url = url_el.text
  824. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  825. f = {
  826. 'format_id': format_id,
  827. 'url': video_url,
  828. 'width': int_or_none(r.attrib.get('width')),
  829. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  830. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  831. 'filesize': filesize,
  832. }
  833. try:
  834. existing_format = next(
  835. fo for fo in formats
  836. if fo['format_id'] == format_id)
  837. except StopIteration:
  838. f.update(self._formats.get(format_id, {}))
  839. formats.append(f)
  840. else:
  841. existing_format.update(f)
  842. except (ExtractorError, KeyError) as e:
  843. self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
  844. self._sort_formats(formats)
  845. return {
  846. 'id': video_id,
  847. 'uploader': video_uploader,
  848. 'uploader_id': video_uploader_id,
  849. 'upload_date': upload_date,
  850. 'title': video_title,
  851. 'thumbnail': video_thumbnail,
  852. 'description': video_description,
  853. 'categories': video_categories,
  854. 'subtitles': video_subtitles,
  855. 'duration': video_duration,
  856. 'age_limit': 18 if age_gate else 0,
  857. 'annotations': video_annotations,
  858. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  859. 'view_count': view_count,
  860. 'like_count': like_count,
  861. 'dislike_count': dislike_count,
  862. 'formats': formats,
  863. }
  864. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  865. IE_DESC = u'YouTube.com playlists'
  866. _VALID_URL = r"""(?x)(?:
  867. (?:https?://)?
  868. (?:\w+\.)?
  869. youtube\.com/
  870. (?:
  871. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  872. \? (?:.*?&)*? (?:p|a|list)=
  873. | p/
  874. )
  875. (
  876. (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  877. # Top tracks, they can also include dots
  878. |(?:MC)[\w\.]*
  879. )
  880. .*
  881. |
  882. ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  883. )"""
  884. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  885. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  886. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  887. IE_NAME = u'youtube:playlist'
  888. def _real_initialize(self):
  889. self._login()
  890. def _ids_to_results(self, ids):
  891. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  892. for vid_id in ids]
  893. def _extract_mix(self, playlist_id):
  894. # The mixes are generated from a a single video
  895. # the id of the playlist is just 'RD' + video_id
  896. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  897. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  898. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  899. title_span = (search_title('playlist-title') or
  900. search_title('title long-title') or search_title('title'))
  901. title = clean_html(title_span)
  902. video_re = r'''(?x)data-video-username=".*?".*?
  903. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id)
  904. ids = orderedSet(re.findall(video_re, webpage, flags=re.DOTALL))
  905. url_results = self._ids_to_results(ids)
  906. return self.playlist_result(url_results, playlist_id, title)
  907. def _real_extract(self, url):
  908. # Extract playlist id
  909. mobj = re.match(self._VALID_URL, url)
  910. if mobj is None:
  911. raise ExtractorError(u'Invalid URL: %s' % url)
  912. playlist_id = mobj.group(1) or mobj.group(2)
  913. # Check if it's a video-specific URL
  914. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  915. if 'v' in query_dict:
  916. video_id = query_dict['v'][0]
  917. if self._downloader.params.get('noplaylist'):
  918. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  919. return self.url_result(video_id, 'Youtube', video_id=video_id)
  920. else:
  921. self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  922. if playlist_id.startswith('RD'):
  923. # Mixes require a custom extraction process
  924. return self._extract_mix(playlist_id)
  925. if playlist_id.startswith('TL'):
  926. raise ExtractorError(u'For downloading YouTube.com top lists, use '
  927. u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  928. url = self._TEMPLATE_URL % playlist_id
  929. page = self._download_webpage(url, playlist_id)
  930. more_widget_html = content_html = page
  931. # Check if the playlist exists or is private
  932. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  933. raise ExtractorError(
  934. u'The playlist doesn\'t exist or is private, use --username or '
  935. '--netrc to access it.',
  936. expected=True)
  937. # Extract the video ids from the playlist pages
  938. ids = []
  939. for page_num in itertools.count(1):
  940. matches = re.finditer(self._VIDEO_RE, content_html)
  941. # We remove the duplicates and the link with index 0
  942. # (it's not the first video of the playlist)
  943. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  944. ids.extend(new_ids)
  945. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  946. if not mobj:
  947. break
  948. more = self._download_json(
  949. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  950. 'Downloading page #%s' % page_num,
  951. transform_source=uppercase_escape)
  952. content_html = more['content_html']
  953. more_widget_html = more['load_more_widget_html']
  954. playlist_title = self._html_search_regex(
  955. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  956. page, u'title')
  957. url_results = self._ids_to_results(ids)
  958. return self.playlist_result(url_results, playlist_id, playlist_title)
  959. class YoutubeTopListIE(YoutubePlaylistIE):
  960. IE_NAME = u'youtube:toplist'
  961. IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  962. u' (Example: "yttoplist:music:Top Tracks")')
  963. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  964. def _real_extract(self, url):
  965. mobj = re.match(self._VALID_URL, url)
  966. channel = mobj.group('chann')
  967. title = mobj.group('title')
  968. query = compat_urllib_parse.urlencode({'title': title})
  969. playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
  970. channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
  971. link = self._html_search_regex(playlist_re, channel_page, u'list')
  972. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  973. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  974. ids = []
  975. # sometimes the webpage doesn't contain the videos
  976. # retry until we get them
  977. for i in itertools.count(0):
  978. msg = u'Downloading Youtube mix'
  979. if i > 0:
  980. msg += ', retry #%d' % i
  981. webpage = self._download_webpage(url, title, msg)
  982. ids = orderedSet(re.findall(video_re, webpage))
  983. if ids:
  984. break
  985. url_results = self._ids_to_results(ids)
  986. return self.playlist_result(url_results, playlist_title=title)
  987. class YoutubeChannelIE(InfoExtractor):
  988. IE_DESC = u'YouTube.com channels'
  989. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  990. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  991. _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'
  992. IE_NAME = u'youtube:channel'
  993. def extract_videos_from_page(self, page):
  994. ids_in_page = []
  995. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  996. if mobj.group(1) not in ids_in_page:
  997. ids_in_page.append(mobj.group(1))
  998. return ids_in_page
  999. def _real_extract(self, url):
  1000. # Extract channel id
  1001. mobj = re.match(self._VALID_URL, url)
  1002. if mobj is None:
  1003. raise ExtractorError(u'Invalid URL: %s' % url)
  1004. # Download channel page
  1005. channel_id = mobj.group(1)
  1006. video_ids = []
  1007. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1008. channel_page = self._download_webpage(url, channel_id)
  1009. autogenerated = re.search(r'''(?x)
  1010. class="[^"]*?(?:
  1011. channel-header-autogenerated-label|
  1012. yt-channel-title-autogenerated
  1013. )[^"]*"''', channel_page) is not None
  1014. if autogenerated:
  1015. # The videos are contained in a single page
  1016. # the ajax pages can't be used, they are empty
  1017. video_ids = self.extract_videos_from_page(channel_page)
  1018. else:
  1019. # Download all channel pages using the json-based channel_ajax query
  1020. for pagenum in itertools.count(1):
  1021. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1022. page = self._download_json(
  1023. url, channel_id, note=u'Downloading page #%s' % pagenum,
  1024. transform_source=uppercase_escape)
  1025. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1026. video_ids.extend(ids_in_page)
  1027. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1028. break
  1029. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1030. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1031. for video_id in video_ids]
  1032. return self.playlist_result(url_entries, channel_id)
  1033. class YoutubeUserIE(InfoExtractor):
  1034. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1035. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1036. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1037. _GDATA_PAGE_SIZE = 50
  1038. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1039. IE_NAME = u'youtube:user'
  1040. @classmethod
  1041. def suitable(cls, url):
  1042. # Don't return True if the url can be extracted with other youtube
  1043. # extractor, the regex would is too permissive and it would match.
  1044. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1045. if any(ie.suitable(url) for ie in other_ies): return False
  1046. else: return super(YoutubeUserIE, cls).suitable(url)
  1047. def _real_extract(self, url):
  1048. # Extract username
  1049. mobj = re.match(self._VALID_URL, url)
  1050. if mobj is None:
  1051. raise ExtractorError(u'Invalid URL: %s' % url)
  1052. username = mobj.group(1)
  1053. # Download video ids using YouTube Data API. Result size per
  1054. # query is limited (currently to 50 videos) so we need to query
  1055. # page by page until there are no video ids - it means we got
  1056. # all of them.
  1057. def download_page(pagenum):
  1058. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1059. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1060. page = self._download_webpage(
  1061. gdata_url, username,
  1062. u'Downloading video ids from %d to %d' % (
  1063. start_index, start_index + self._GDATA_PAGE_SIZE))
  1064. try:
  1065. response = json.loads(page)
  1066. except ValueError as err:
  1067. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1068. if 'entry' not in response['feed']:
  1069. return
  1070. # Extract video identifiers
  1071. entries = response['feed']['entry']
  1072. for entry in entries:
  1073. title = entry['title']['$t']
  1074. video_id = entry['id']['$t'].split('/')[-1]
  1075. yield {
  1076. '_type': 'url',
  1077. 'url': video_id,
  1078. 'ie_key': 'Youtube',
  1079. 'id': video_id,
  1080. 'title': title,
  1081. }
  1082. url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
  1083. return self.playlist_result(url_results, playlist_title=username)
  1084. class YoutubeSearchIE(SearchInfoExtractor):
  1085. IE_DESC = u'YouTube.com searches'
  1086. _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1087. _MAX_RESULTS = 1000
  1088. IE_NAME = u'youtube:search'
  1089. _SEARCH_KEY = 'ytsearch'
  1090. def _get_n_results(self, query, n):
  1091. """Get a specified number of results for a query"""
  1092. video_ids = []
  1093. pagenum = 0
  1094. limit = n
  1095. PAGE_SIZE = 50
  1096. while (PAGE_SIZE * pagenum) < limit:
  1097. result_url = self._API_URL % (
  1098. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1099. (PAGE_SIZE * pagenum) + 1)
  1100. data_json = self._download_webpage(
  1101. result_url, video_id=u'query "%s"' % query,
  1102. note=u'Downloading page %s' % (pagenum + 1),
  1103. errnote=u'Unable to download API page')
  1104. data = json.loads(data_json)
  1105. api_response = data['data']
  1106. if 'items' not in api_response:
  1107. raise ExtractorError(
  1108. u'[youtube] No video results', expected=True)
  1109. new_ids = list(video['id'] for video in api_response['items'])
  1110. video_ids += new_ids
  1111. limit = min(n, api_response['totalItems'])
  1112. pagenum += 1
  1113. if len(video_ids) > n:
  1114. video_ids = video_ids[:n]
  1115. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1116. for video_id in video_ids]
  1117. return self.playlist_result(videos, query)
  1118. class YoutubeSearchDateIE(YoutubeSearchIE):
  1119. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1120. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1121. _SEARCH_KEY = 'ytsearchdate'
  1122. IE_DESC = u'YouTube.com searches, newest videos first'
  1123. class YoutubeSearchURLIE(InfoExtractor):
  1124. IE_DESC = u'YouTube.com search URLs'
  1125. IE_NAME = u'youtube:search_url'
  1126. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1127. def _real_extract(self, url):
  1128. mobj = re.match(self._VALID_URL, url)
  1129. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1130. webpage = self._download_webpage(url, query)
  1131. result_code = self._search_regex(
  1132. r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
  1133. part_codes = re.findall(
  1134. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1135. entries = []
  1136. for part_code in part_codes:
  1137. part_title = self._html_search_regex(
  1138. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1139. part_url_snippet = self._html_search_regex(
  1140. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1141. part_url = compat_urlparse.urljoin(
  1142. 'https://www.youtube.com/', part_url_snippet)
  1143. entries.append({
  1144. '_type': 'url',
  1145. 'url': part_url,
  1146. 'title': part_title,
  1147. })
  1148. return {
  1149. '_type': 'playlist',
  1150. 'entries': entries,
  1151. 'title': query,
  1152. }
  1153. class YoutubeShowIE(InfoExtractor):
  1154. IE_DESC = u'YouTube.com (multi-season) shows'
  1155. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1156. IE_NAME = u'youtube:show'
  1157. def _real_extract(self, url):
  1158. mobj = re.match(self._VALID_URL, url)
  1159. show_name = mobj.group(1)
  1160. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1161. # There's one playlist for each season of the show
  1162. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1163. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1164. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1165. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1166. """
  1167. Base class for extractors that fetch info from
  1168. http://www.youtube.com/feed_ajax
  1169. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1170. """
  1171. _LOGIN_REQUIRED = True
  1172. # use action_load_personal_feed instead of action_load_system_feed
  1173. _PERSONAL_FEED = False
  1174. @property
  1175. def _FEED_TEMPLATE(self):
  1176. action = 'action_load_system_feed'
  1177. if self._PERSONAL_FEED:
  1178. action = 'action_load_personal_feed'
  1179. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1180. @property
  1181. def IE_NAME(self):
  1182. return u'youtube:%s' % self._FEED_NAME
  1183. def _real_initialize(self):
  1184. self._login()
  1185. def _real_extract(self, url):
  1186. feed_entries = []
  1187. paging = 0
  1188. for i in itertools.count(1):
  1189. info = self._download_json(self._FEED_TEMPLATE % paging,
  1190. u'%s feed' % self._FEED_NAME,
  1191. u'Downloading page %s' % i)
  1192. feed_html = info.get('feed_html') or info.get('content_html')
  1193. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1194. ids = orderedSet(m.group(1) for m in m_ids)
  1195. feed_entries.extend(
  1196. self.url_result(video_id, 'Youtube', video_id=video_id)
  1197. for video_id in ids)
  1198. mobj = re.search(
  1199. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1200. feed_html)
  1201. if mobj is None:
  1202. break
  1203. paging = mobj.group('paging')
  1204. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1205. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1206. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1207. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1208. _FEED_NAME = 'subscriptions'
  1209. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1210. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1211. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1212. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1213. _FEED_NAME = 'recommended'
  1214. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1215. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1216. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1217. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1218. _FEED_NAME = 'watch_later'
  1219. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1220. _PERSONAL_FEED = True
  1221. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1222. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1223. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1224. _FEED_NAME = 'history'
  1225. _PERSONAL_FEED = True
  1226. _PLAYLIST_TITLE = u'Youtube Watch History'
  1227. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1228. IE_NAME = u'youtube:favorites'
  1229. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1230. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1231. _LOGIN_REQUIRED = True
  1232. def _real_extract(self, url):
  1233. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1234. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1235. return self.url_result(playlist_id, 'YoutubePlaylist')
  1236. class YoutubeTruncatedURLIE(InfoExtractor):
  1237. IE_NAME = 'youtube:truncated_url'
  1238. IE_DESC = False # Do not list
  1239. _VALID_URL = r'''(?x)
  1240. (?:https?://)?[^/]+/watch\?(?:
  1241. feature=[a-z_]+|
  1242. annotation_id=annotation_[^&]+
  1243. )?$|
  1244. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1245. '''
  1246. _TESTS = [{
  1247. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1248. 'only_matching': True,
  1249. }, {
  1250. 'url': 'http://www.youtube.com/watch?',
  1251. 'only_matching': True,
  1252. }]
  1253. def _real_extract(self, url):
  1254. raise ExtractorError(
  1255. u'Did you forget to quote the URL? Remember that & is a meta '
  1256. u'character in most shells, so you want to put the URL in quotes, '
  1257. u'like youtube-dl '
  1258. u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1259. u' or simply youtube-dl BaW_jenozKc .',
  1260. expected=True)