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.

795 lines
34 KiB

  1. # coding: utf-8
  2. import json
  3. import netrc
  4. import re
  5. import socket
  6. from .common import InfoExtractor, SearchInfoExtractor
  7. from ..utils import (
  8. compat_http_client,
  9. compat_parse_qs,
  10. compat_urllib_error,
  11. compat_urllib_parse,
  12. compat_urllib_request,
  13. compat_str,
  14. clean_html,
  15. get_element_by_id,
  16. ExtractorError,
  17. unescapeHTML,
  18. unified_strdate,
  19. )
  20. class YoutubeIE(InfoExtractor):
  21. """Information extractor for youtube.com."""
  22. _VALID_URL = r"""^
  23. (
  24. (?:https?://)? # http(s):// (optional)
  25. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  26. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  27. (?:.*?\#/)? # handle anchor (#/) redirect urls
  28. (?: # the various things that can precede the ID:
  29. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  30. |(?: # or the v= param in all its forms
  31. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  32. (?:\?|\#!?) # the params delimiter ? or # or #!
  33. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  34. v=
  35. )
  36. )? # optional -> youtube.com/xxxx is OK
  37. )? # all until now is optional -> you can pass the naked ID
  38. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  39. (?(1).+)? # if we found the ID, everything can follow
  40. $"""
  41. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  42. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  43. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  44. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  45. _NETRC_MACHINE = 'youtube'
  46. # Listed in order of quality
  47. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  48. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  49. _video_extensions = {
  50. '13': '3gp',
  51. '17': 'mp4',
  52. '18': 'mp4',
  53. '22': 'mp4',
  54. '37': 'mp4',
  55. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  56. '43': 'webm',
  57. '44': 'webm',
  58. '45': 'webm',
  59. '46': 'webm',
  60. }
  61. _video_dimensions = {
  62. '5': '240x400',
  63. '6': '???',
  64. '13': '???',
  65. '17': '144x176',
  66. '18': '360x640',
  67. '22': '720x1280',
  68. '34': '360x640',
  69. '35': '480x854',
  70. '37': '1080x1920',
  71. '38': '3072x4096',
  72. '43': '360x640',
  73. '44': '480x854',
  74. '45': '720x1280',
  75. '46': '1080x1920',
  76. }
  77. IE_NAME = u'youtube'
  78. @classmethod
  79. def suitable(cls, url):
  80. """Receives a URL and returns True if suitable for this IE."""
  81. if YoutubePlaylistIE.suitable(url): return False
  82. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  83. def report_lang(self):
  84. """Report attempt to set language."""
  85. self.to_screen(u'Setting language')
  86. def report_login(self):
  87. """Report attempt to log in."""
  88. self.to_screen(u'Logging in')
  89. def report_video_webpage_download(self, video_id):
  90. """Report attempt to download video webpage."""
  91. self.to_screen(u'%s: Downloading video webpage' % video_id)
  92. def report_video_info_webpage_download(self, video_id):
  93. """Report attempt to download video info webpage."""
  94. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  95. def report_video_subtitles_download(self, video_id):
  96. """Report attempt to download video info webpage."""
  97. self.to_screen(u'%s: Checking available subtitles' % video_id)
  98. def report_video_subtitles_request(self, video_id, sub_lang, format):
  99. """Report attempt to download video info webpage."""
  100. self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
  101. def report_video_subtitles_available(self, video_id, sub_lang_list):
  102. """Report available subtitles."""
  103. sub_lang = ",".join(list(sub_lang_list.keys()))
  104. self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang))
  105. def report_information_extraction(self, video_id):
  106. """Report attempt to extract video information."""
  107. self.to_screen(u'%s: Extracting video information' % video_id)
  108. def report_unavailable_format(self, video_id, format):
  109. """Report extracted video URL."""
  110. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  111. def report_rtmp_download(self):
  112. """Indicate the download will use the RTMP protocol."""
  113. self.to_screen(u'RTMP download detected')
  114. @staticmethod
  115. def _decrypt_signature(s):
  116. """Decrypt the key the two subkeys must have a length of 43"""
  117. (a,b) = s.split('.')
  118. if len(a) != 43 or len(b) != 43:
  119. raise ExtractorError(u'Unable to decrypt signature, subkeys lengths not valid')
  120. b = ''.join([b[:8],a[0],b[9:18],b[-4],b[19:39], b[18]])[0:40]
  121. a = a[-40:]
  122. s_dec = '.'.join((a,b))[::-1]
  123. return s_dec
  124. def _get_available_subtitles(self, video_id):
  125. self.report_video_subtitles_download(video_id)
  126. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  127. try:
  128. sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  129. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  130. return (u'unable to download video subtitles: %s' % compat_str(err), None)
  131. sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  132. sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
  133. if not sub_lang_list:
  134. return (u'video doesn\'t have subtitles', None)
  135. return sub_lang_list
  136. def _list_available_subtitles(self, video_id):
  137. sub_lang_list = self._get_available_subtitles(video_id)
  138. self.report_video_subtitles_available(video_id, sub_lang_list)
  139. def _request_subtitle(self, sub_lang, sub_name, video_id, format):
  140. """
  141. Return tuple:
  142. (error_message, sub_lang, sub)
  143. """
  144. self.report_video_subtitles_request(video_id, sub_lang, format)
  145. params = compat_urllib_parse.urlencode({
  146. 'lang': sub_lang,
  147. 'name': sub_name,
  148. 'v': video_id,
  149. 'fmt': format,
  150. })
  151. url = 'http://www.youtube.com/api/timedtext?' + params
  152. try:
  153. sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
  154. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  155. return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
  156. if not sub:
  157. return (u'Did not fetch video subtitles', None, None)
  158. return (None, sub_lang, sub)
  159. def _request_automatic_caption(self, video_id, webpage):
  160. """We need the webpage for getting the captions url, pass it as an
  161. argument to speed up the process."""
  162. sub_lang = self._downloader.params.get('subtitleslang') or 'en'
  163. sub_format = self._downloader.params.get('subtitlesformat')
  164. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  165. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  166. err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
  167. if mobj is None:
  168. return [(err_msg, None, None)]
  169. player_config = json.loads(mobj.group(1))
  170. try:
  171. args = player_config[u'args']
  172. caption_url = args[u'ttsurl']
  173. timestamp = args[u'timestamp']
  174. params = compat_urllib_parse.urlencode({
  175. 'lang': 'en',
  176. 'tlang': sub_lang,
  177. 'fmt': sub_format,
  178. 'ts': timestamp,
  179. 'kind': 'asr',
  180. })
  181. subtitles_url = caption_url + '&' + params
  182. sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
  183. return [(None, sub_lang, sub)]
  184. except KeyError:
  185. return [(err_msg, None, None)]
  186. def _extract_subtitle(self, video_id):
  187. """
  188. Return a list with a tuple:
  189. [(error_message, sub_lang, sub)]
  190. """
  191. sub_lang_list = self._get_available_subtitles(video_id)
  192. sub_format = self._downloader.params.get('subtitlesformat')
  193. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  194. return [(sub_lang_list[0], None, None)]
  195. if self._downloader.params.get('subtitleslang', False):
  196. sub_lang = self._downloader.params.get('subtitleslang')
  197. elif 'en' in sub_lang_list:
  198. sub_lang = 'en'
  199. else:
  200. sub_lang = list(sub_lang_list.keys())[0]
  201. if not sub_lang in sub_lang_list:
  202. return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
  203. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  204. return [subtitle]
  205. def _extract_all_subtitles(self, video_id):
  206. sub_lang_list = self._get_available_subtitles(video_id)
  207. sub_format = self._downloader.params.get('subtitlesformat')
  208. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  209. return [(sub_lang_list[0], None, None)]
  210. subtitles = []
  211. for sub_lang in sub_lang_list:
  212. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  213. subtitles.append(subtitle)
  214. return subtitles
  215. def _print_formats(self, formats):
  216. print('Available formats:')
  217. for x in formats:
  218. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  219. def _real_initialize(self):
  220. if self._downloader is None:
  221. return
  222. username = None
  223. password = None
  224. downloader_params = self._downloader.params
  225. # Attempt to use provided username and password or .netrc data
  226. if downloader_params.get('username', None) is not None:
  227. username = downloader_params['username']
  228. password = downloader_params['password']
  229. elif downloader_params.get('usenetrc', False):
  230. try:
  231. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  232. if info is not None:
  233. username = info[0]
  234. password = info[2]
  235. else:
  236. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  237. except (IOError, netrc.NetrcParseError) as err:
  238. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  239. return
  240. # Set language
  241. request = compat_urllib_request.Request(self._LANG_URL)
  242. try:
  243. self.report_lang()
  244. compat_urllib_request.urlopen(request).read()
  245. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  246. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  247. return
  248. # No authentication to be performed
  249. if username is None:
  250. return
  251. request = compat_urllib_request.Request(self._LOGIN_URL)
  252. try:
  253. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  254. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  255. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  256. return
  257. galx = None
  258. dsh = None
  259. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  260. if match:
  261. galx = match.group(1)
  262. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  263. if match:
  264. dsh = match.group(1)
  265. # Log in
  266. login_form_strs = {
  267. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  268. u'Email': username,
  269. u'GALX': galx,
  270. u'Passwd': password,
  271. u'PersistentCookie': u'yes',
  272. u'_utf8': u'',
  273. u'bgresponse': u'js_disabled',
  274. u'checkConnection': u'',
  275. u'checkedDomains': u'youtube',
  276. u'dnConn': u'',
  277. u'dsh': dsh,
  278. u'pstMsg': u'0',
  279. u'rmShown': u'1',
  280. u'secTok': u'',
  281. u'signIn': u'Sign in',
  282. u'timeStmp': u'',
  283. u'service': u'youtube',
  284. u'uilel': u'3',
  285. u'hl': u'en_US',
  286. }
  287. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  288. # chokes on unicode
  289. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  290. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  291. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  292. try:
  293. self.report_login()
  294. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  295. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  296. self._downloader.report_warning(u'unable to log in: bad username or password')
  297. return
  298. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  299. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  300. return
  301. # Confirm age
  302. age_form = {
  303. 'next_url': '/',
  304. 'action_confirm': 'Confirm',
  305. }
  306. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  307. try:
  308. self.report_age_confirmation()
  309. compat_urllib_request.urlopen(request).read().decode('utf-8')
  310. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  311. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  312. def _extract_id(self, url):
  313. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  314. if mobj is None:
  315. raise ExtractorError(u'Invalid URL: %s' % url)
  316. video_id = mobj.group(2)
  317. return video_id
  318. def _real_extract(self, url):
  319. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  320. mobj = re.search(self._NEXT_URL_RE, url)
  321. if mobj:
  322. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  323. video_id = self._extract_id(url)
  324. # Get video webpage
  325. self.report_video_webpage_download(video_id)
  326. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  327. request = compat_urllib_request.Request(url)
  328. try:
  329. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  330. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  331. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  332. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  333. # Attempt to extract SWF player URL
  334. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  335. if mobj is not None:
  336. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  337. else:
  338. player_url = None
  339. # Get video info
  340. self.report_video_info_webpage_download(video_id)
  341. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  342. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  343. % (video_id, el_type))
  344. video_info_webpage = self._download_webpage(video_info_url, video_id,
  345. note=False,
  346. errnote='unable to download video info webpage')
  347. video_info = compat_parse_qs(video_info_webpage)
  348. if 'token' in video_info:
  349. break
  350. if 'token' not in video_info:
  351. if 'reason' in video_info:
  352. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0])
  353. else:
  354. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  355. # Check for "rental" videos
  356. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  357. raise ExtractorError(u'"rental" videos not supported')
  358. # Start extracting information
  359. self.report_information_extraction(video_id)
  360. # uploader
  361. if 'author' not in video_info:
  362. raise ExtractorError(u'Unable to extract uploader name')
  363. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  364. # uploader_id
  365. video_uploader_id = None
  366. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  367. if mobj is not None:
  368. video_uploader_id = mobj.group(1)
  369. else:
  370. self._downloader.report_warning(u'unable to extract uploader nickname')
  371. # title
  372. if 'title' not in video_info:
  373. raise ExtractorError(u'Unable to extract video title')
  374. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  375. # thumbnail image
  376. if 'thumbnail_url' not in video_info:
  377. self._downloader.report_warning(u'unable to extract video thumbnail')
  378. video_thumbnail = ''
  379. else: # don't panic if we can't find it
  380. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  381. # upload date
  382. upload_date = None
  383. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  384. if mobj is not None:
  385. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  386. upload_date = unified_strdate(upload_date)
  387. # description
  388. video_description = get_element_by_id("eow-description", video_webpage)
  389. if video_description:
  390. video_description = clean_html(video_description)
  391. else:
  392. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  393. if fd_mobj:
  394. video_description = unescapeHTML(fd_mobj.group(1))
  395. else:
  396. video_description = u''
  397. # subtitles
  398. video_subtitles = None
  399. if self._downloader.params.get('writesubtitles', False):
  400. video_subtitles = self._extract_subtitle(video_id)
  401. if video_subtitles:
  402. (sub_error, sub_lang, sub) = video_subtitles[0]
  403. if sub_error:
  404. # We try with the automatic captions
  405. video_subtitles = self._request_automatic_caption(video_id, video_webpage)
  406. (sub_error_auto, sub_lang, sub) = video_subtitles[0]
  407. if sub is not None:
  408. pass
  409. else:
  410. # We report the original error
  411. self._downloader.report_warning(sub_error)
  412. if self._downloader.params.get('allsubtitles', False):
  413. video_subtitles = self._extract_all_subtitles(video_id)
  414. for video_subtitle in video_subtitles:
  415. (sub_error, sub_lang, sub) = video_subtitle
  416. if sub_error:
  417. self._downloader.report_warning(sub_error)
  418. if self._downloader.params.get('listsubtitles', False):
  419. self._list_available_subtitles(video_id)
  420. return
  421. if 'length_seconds' not in video_info:
  422. self._downloader.report_warning(u'unable to extract video duration')
  423. video_duration = ''
  424. else:
  425. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  426. # Decide which formats to download
  427. req_format = self._downloader.params.get('format', None)
  428. try:
  429. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  430. info = json.loads(mobj.group(1))
  431. args = info['args']
  432. if args.get('ptk','') == 'vevo' or 'dashmpd':
  433. # Vevo videos with encrypted signatures
  434. self.to_screen(u'%s: Vevo video detected.' % video_id)
  435. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  436. except ValueError:
  437. pass
  438. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  439. self.report_rtmp_download()
  440. video_url_list = [(None, video_info['conn'][0])]
  441. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  442. url_map = {}
  443. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  444. url_data = compat_parse_qs(url_data_str)
  445. if 'itag' in url_data and 'url' in url_data:
  446. url = url_data['url'][0]
  447. if 'sig' in url_data:
  448. url += '&signature=' + url_data['sig'][0]
  449. elif 's' in url_data:
  450. signature = self._decrypt_signature(url_data['s'][0])
  451. url += '&signature=' + signature
  452. if 'ratebypass' not in url:
  453. url += '&ratebypass=yes'
  454. url_map[url_data['itag'][0]] = url
  455. format_limit = self._downloader.params.get('format_limit', None)
  456. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  457. if format_limit is not None and format_limit in available_formats:
  458. format_list = available_formats[available_formats.index(format_limit):]
  459. else:
  460. format_list = available_formats
  461. existing_formats = [x for x in format_list if x in url_map]
  462. if len(existing_formats) == 0:
  463. raise ExtractorError(u'no known formats available for video')
  464. if self._downloader.params.get('listformats', None):
  465. self._print_formats(existing_formats)
  466. return
  467. if req_format is None or req_format == 'best':
  468. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  469. elif req_format == 'worst':
  470. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  471. elif req_format in ('-1', 'all'):
  472. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  473. else:
  474. # Specific formats. We pick the first in a slash-delimeted sequence.
  475. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  476. req_formats = req_format.split('/')
  477. video_url_list = None
  478. for rf in req_formats:
  479. if rf in url_map:
  480. video_url_list = [(rf, url_map[rf])]
  481. break
  482. if video_url_list is None:
  483. raise ExtractorError(u'requested format not available')
  484. else:
  485. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  486. results = []
  487. for format_param, video_real_url in video_url_list:
  488. # Extension
  489. video_extension = self._video_extensions.get(format_param, 'flv')
  490. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  491. self._video_dimensions.get(format_param, '???'))
  492. results.append({
  493. 'id': video_id,
  494. 'url': video_real_url,
  495. 'uploader': video_uploader,
  496. 'uploader_id': video_uploader_id,
  497. 'upload_date': upload_date,
  498. 'title': video_title,
  499. 'ext': video_extension,
  500. 'format': video_format,
  501. 'thumbnail': video_thumbnail,
  502. 'description': video_description,
  503. 'player_url': player_url,
  504. 'subtitles': video_subtitles,
  505. 'duration': video_duration
  506. })
  507. return results
  508. class YoutubePlaylistIE(InfoExtractor):
  509. """Information Extractor for YouTube playlists."""
  510. _VALID_URL = r"""(?:
  511. (?:https?://)?
  512. (?:\w+\.)?
  513. youtube\.com/
  514. (?:
  515. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  516. \? (?:.*?&)*? (?:p|a|list)=
  517. | p/
  518. )
  519. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  520. .*
  521. |
  522. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  523. )"""
  524. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  525. _MAX_RESULTS = 50
  526. IE_NAME = u'youtube:playlist'
  527. @classmethod
  528. def suitable(cls, url):
  529. """Receives a URL and returns True if suitable for this IE."""
  530. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  531. def _real_extract(self, url):
  532. # Extract playlist id
  533. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  534. if mobj is None:
  535. raise ExtractorError(u'Invalid URL: %s' % url)
  536. # Download playlist videos from API
  537. playlist_id = mobj.group(1) or mobj.group(2)
  538. page_num = 1
  539. videos = []
  540. while True:
  541. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  542. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  543. try:
  544. response = json.loads(page)
  545. except ValueError as err:
  546. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  547. if 'feed' not in response:
  548. raise ExtractorError(u'Got a malformed response from YouTube API')
  549. playlist_title = response['feed']['title']['$t']
  550. if 'entry' not in response['feed']:
  551. # Number of videos is a multiple of self._MAX_RESULTS
  552. break
  553. for entry in response['feed']['entry']:
  554. index = entry['yt$position']['$t']
  555. if 'media$group' in entry and 'media$player' in entry['media$group']:
  556. videos.append((index, entry['media$group']['media$player']['url']))
  557. if len(response['feed']['entry']) < self._MAX_RESULTS:
  558. break
  559. page_num += 1
  560. videos = [v[1] for v in sorted(videos)]
  561. url_results = [self.url_result(url, 'Youtube') for url in videos]
  562. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  563. class YoutubeChannelIE(InfoExtractor):
  564. """Information Extractor for YouTube channels."""
  565. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  566. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  567. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  568. _MORE_PAGES_URL = 'http://www.youtube.com/channel_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  569. IE_NAME = u'youtube:channel'
  570. def extract_videos_from_page(self, page):
  571. ids_in_page = []
  572. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  573. if mobj.group(1) not in ids_in_page:
  574. ids_in_page.append(mobj.group(1))
  575. return ids_in_page
  576. def _real_extract(self, url):
  577. # Extract channel id
  578. mobj = re.match(self._VALID_URL, url)
  579. if mobj is None:
  580. raise ExtractorError(u'Invalid URL: %s' % url)
  581. # Download channel page
  582. channel_id = mobj.group(1)
  583. video_ids = []
  584. pagenum = 1
  585. url = self._TEMPLATE_URL % (channel_id, pagenum)
  586. page = self._download_webpage(url, channel_id,
  587. u'Downloading page #%s' % pagenum)
  588. # Extract video identifiers
  589. ids_in_page = self.extract_videos_from_page(page)
  590. video_ids.extend(ids_in_page)
  591. # Download any subsequent channel pages using the json-based channel_ajax query
  592. if self._MORE_PAGES_INDICATOR in page:
  593. while True:
  594. pagenum = pagenum + 1
  595. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  596. page = self._download_webpage(url, channel_id,
  597. u'Downloading page #%s' % pagenum)
  598. page = json.loads(page)
  599. ids_in_page = self.extract_videos_from_page(page['content_html'])
  600. video_ids.extend(ids_in_page)
  601. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  602. break
  603. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  604. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  605. url_entries = [self.url_result(url, 'Youtube') for url in urls]
  606. return [self.playlist_result(url_entries, channel_id)]
  607. class YoutubeUserIE(InfoExtractor):
  608. """Information Extractor for YouTube users."""
  609. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  610. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  611. _GDATA_PAGE_SIZE = 50
  612. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  613. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  614. IE_NAME = u'youtube:user'
  615. def _real_extract(self, url):
  616. # Extract username
  617. mobj = re.match(self._VALID_URL, url)
  618. if mobj is None:
  619. raise ExtractorError(u'Invalid URL: %s' % url)
  620. username = mobj.group(1)
  621. # Download video ids using YouTube Data API. Result size per
  622. # query is limited (currently to 50 videos) so we need to query
  623. # page by page until there are no video ids - it means we got
  624. # all of them.
  625. video_ids = []
  626. pagenum = 0
  627. while True:
  628. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  629. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  630. page = self._download_webpage(gdata_url, username,
  631. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  632. # Extract video identifiers
  633. ids_in_page = []
  634. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  635. if mobj.group(1) not in ids_in_page:
  636. ids_in_page.append(mobj.group(1))
  637. video_ids.extend(ids_in_page)
  638. # A little optimization - if current page is not
  639. # "full", ie. does not contain PAGE_SIZE video ids then
  640. # we can assume that this page is the last one - there
  641. # are no more ids on further pages - no need to query
  642. # again.
  643. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  644. break
  645. pagenum += 1
  646. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  647. url_results = [self.url_result(url, 'Youtube') for url in urls]
  648. return [self.playlist_result(url_results, playlist_title = username)]
  649. class YoutubeSearchIE(SearchInfoExtractor):
  650. """Information Extractor for YouTube search queries."""
  651. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  652. _MAX_RESULTS = 1000
  653. IE_NAME = u'youtube:search'
  654. _SEARCH_KEY = 'ytsearch'
  655. def report_download_page(self, query, pagenum):
  656. """Report attempt to download search page with given number."""
  657. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  658. def _get_n_results(self, query, n):
  659. """Get a specified number of results for a query"""
  660. video_ids = []
  661. pagenum = 0
  662. limit = n
  663. while (50 * pagenum) < limit:
  664. self.report_download_page(query, pagenum+1)
  665. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  666. request = compat_urllib_request.Request(result_url)
  667. try:
  668. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  669. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  670. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  671. api_response = json.loads(data)['data']
  672. if not 'items' in api_response:
  673. raise ExtractorError(u'[youtube] No video results')
  674. new_ids = list(video['id'] for video in api_response['items'])
  675. video_ids += new_ids
  676. limit = min(n, api_response['totalItems'])
  677. pagenum += 1
  678. if len(video_ids) > n:
  679. video_ids = video_ids[:n]
  680. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  681. return self.playlist_result(videos, query)