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.

1838 lines
80 KiB

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