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.

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