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.

855 lines
38 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. if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
  365. self._downloader.report_warning(u'Did you forget to quote the URL? Remember that & is a meta-character in most shells, so you want to put the URL in quotes, like youtube-dl \'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\' (or simply youtube-dl BaW_jenozKc ).')
  366. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  367. mobj = re.search(self._NEXT_URL_RE, url)
  368. if mobj:
  369. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  370. video_id = self._extract_id(url)
  371. # Get video webpage
  372. self.report_video_webpage_download(video_id)
  373. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  374. request = compat_urllib_request.Request(url)
  375. try:
  376. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  377. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  378. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  379. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  380. # Attempt to extract SWF player URL
  381. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  382. if mobj is not None:
  383. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  384. else:
  385. player_url = None
  386. # Get video info
  387. self.report_video_info_webpage_download(video_id)
  388. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  389. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  390. % (video_id, el_type))
  391. video_info_webpage = self._download_webpage(video_info_url, video_id,
  392. note=False,
  393. errnote='unable to download video info webpage')
  394. video_info = compat_parse_qs(video_info_webpage)
  395. if 'token' in video_info:
  396. break
  397. if 'token' not in video_info:
  398. if 'reason' in video_info:
  399. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0])
  400. else:
  401. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  402. # Check for "rental" videos
  403. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  404. raise ExtractorError(u'"rental" videos not supported')
  405. # Start extracting information
  406. self.report_information_extraction(video_id)
  407. # uploader
  408. if 'author' not in video_info:
  409. raise ExtractorError(u'Unable to extract uploader name')
  410. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  411. # uploader_id
  412. video_uploader_id = None
  413. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  414. if mobj is not None:
  415. video_uploader_id = mobj.group(1)
  416. else:
  417. self._downloader.report_warning(u'unable to extract uploader nickname')
  418. # title
  419. if 'title' not in video_info:
  420. raise ExtractorError(u'Unable to extract video title')
  421. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  422. # thumbnail image
  423. if 'thumbnail_url' not in video_info:
  424. self._downloader.report_warning(u'unable to extract video thumbnail')
  425. video_thumbnail = ''
  426. else: # don't panic if we can't find it
  427. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  428. # upload date
  429. upload_date = None
  430. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  431. if mobj is not None:
  432. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  433. upload_date = unified_strdate(upload_date)
  434. # description
  435. video_description = get_element_by_id("eow-description", video_webpage)
  436. if video_description:
  437. video_description = clean_html(video_description)
  438. else:
  439. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  440. if fd_mobj:
  441. video_description = unescapeHTML(fd_mobj.group(1))
  442. else:
  443. video_description = u''
  444. # subtitles
  445. video_subtitles = None
  446. if self._downloader.params.get('writesubtitles', False):
  447. video_subtitles = self._extract_subtitle(video_id)
  448. if video_subtitles:
  449. (sub_error, sub_lang, sub) = video_subtitles[0]
  450. if sub_error:
  451. self._downloader.report_warning(sub_error)
  452. if self._downloader.params.get('writeautomaticsub', False):
  453. video_subtitles = self._request_automatic_caption(video_id, video_webpage)
  454. (sub_error, sub_lang, sub) = video_subtitles[0]
  455. if sub_error:
  456. self._downloader.report_warning(sub_error)
  457. if self._downloader.params.get('allsubtitles', False):
  458. video_subtitles = self._extract_all_subtitles(video_id)
  459. for video_subtitle in video_subtitles:
  460. (sub_error, sub_lang, sub) = video_subtitle
  461. if sub_error:
  462. self._downloader.report_warning(sub_error)
  463. if self._downloader.params.get('listsubtitles', False):
  464. self._list_available_subtitles(video_id)
  465. return
  466. if 'length_seconds' not in video_info:
  467. self._downloader.report_warning(u'unable to extract video duration')
  468. video_duration = ''
  469. else:
  470. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  471. # Decide which formats to download
  472. req_format = self._downloader.params.get('format', None)
  473. try:
  474. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  475. if not mobj:
  476. raise ValueError('Could not find vevo ID')
  477. info = json.loads(mobj.group(1))
  478. args = info['args']
  479. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  480. # this signatures are encrypted
  481. m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
  482. if m_s is not None:
  483. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  484. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  485. except ValueError:
  486. pass
  487. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  488. self.report_rtmp_download()
  489. video_url_list = [(None, video_info['conn'][0])]
  490. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  491. url_map = {}
  492. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  493. url_data = compat_parse_qs(url_data_str)
  494. if 'itag' in url_data and 'url' in url_data:
  495. url = url_data['url'][0]
  496. if 'sig' in url_data:
  497. url += '&signature=' + url_data['sig'][0]
  498. elif 's' in url_data:
  499. if self._downloader.params.get('verbose'):
  500. s = url_data['s'][0]
  501. player = self._search_regex(r'html5player-(.+?)\.js', video_webpage,
  502. 'html5 player', fatal=False)
  503. self.to_screen('encrypted signature length %d (%d.%d), itag %s, html5 player %s' %
  504. (len(s), len(s.split('.')[0]), len(s.split('.')[1]), url_data['itag'][0], player))
  505. signature = self._decrypt_signature(url_data['s'][0])
  506. url += '&signature=' + signature
  507. if 'ratebypass' not in url:
  508. url += '&ratebypass=yes'
  509. url_map[url_data['itag'][0]] = url
  510. format_limit = self._downloader.params.get('format_limit', None)
  511. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  512. if format_limit is not None and format_limit in available_formats:
  513. format_list = available_formats[available_formats.index(format_limit):]
  514. else:
  515. format_list = available_formats
  516. existing_formats = [x for x in format_list if x in url_map]
  517. if len(existing_formats) == 0:
  518. raise ExtractorError(u'no known formats available for video')
  519. if self._downloader.params.get('listformats', None):
  520. self._print_formats(existing_formats)
  521. return
  522. if req_format is None or req_format == 'best':
  523. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  524. elif req_format == 'worst':
  525. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  526. elif req_format in ('-1', 'all'):
  527. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  528. else:
  529. # Specific formats. We pick the first in a slash-delimeted sequence.
  530. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  531. req_formats = req_format.split('/')
  532. video_url_list = None
  533. for rf in req_formats:
  534. if rf in url_map:
  535. video_url_list = [(rf, url_map[rf])]
  536. break
  537. if video_url_list is None:
  538. raise ExtractorError(u'requested format not available')
  539. else:
  540. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  541. results = []
  542. for format_param, video_real_url in video_url_list:
  543. # Extension
  544. video_extension = self._video_extensions.get(format_param, 'flv')
  545. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  546. self._video_dimensions.get(format_param, '???'))
  547. results.append({
  548. 'id': video_id,
  549. 'url': video_real_url,
  550. 'uploader': video_uploader,
  551. 'uploader_id': video_uploader_id,
  552. 'upload_date': upload_date,
  553. 'title': video_title,
  554. 'ext': video_extension,
  555. 'format': video_format,
  556. 'thumbnail': video_thumbnail,
  557. 'description': video_description,
  558. 'player_url': player_url,
  559. 'subtitles': video_subtitles,
  560. 'duration': video_duration
  561. })
  562. return results
  563. class YoutubePlaylistIE(InfoExtractor):
  564. """Information Extractor for YouTube playlists."""
  565. _VALID_URL = r"""(?:
  566. (?:https?://)?
  567. (?:\w+\.)?
  568. youtube\.com/
  569. (?:
  570. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  571. \? (?:.*?&)*? (?:p|a|list)=
  572. | p/
  573. )
  574. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  575. .*
  576. |
  577. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  578. )"""
  579. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  580. _MAX_RESULTS = 50
  581. IE_NAME = u'youtube:playlist'
  582. @classmethod
  583. def suitable(cls, url):
  584. """Receives a URL and returns True if suitable for this IE."""
  585. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  586. def _real_extract(self, url):
  587. # Extract playlist id
  588. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  589. if mobj is None:
  590. raise ExtractorError(u'Invalid URL: %s' % url)
  591. # Download playlist videos from API
  592. playlist_id = mobj.group(1) or mobj.group(2)
  593. page_num = 1
  594. videos = []
  595. while True:
  596. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  597. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  598. try:
  599. response = json.loads(page)
  600. except ValueError as err:
  601. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  602. if 'feed' not in response:
  603. raise ExtractorError(u'Got a malformed response from YouTube API')
  604. playlist_title = response['feed']['title']['$t']
  605. if 'entry' not in response['feed']:
  606. # Number of videos is a multiple of self._MAX_RESULTS
  607. break
  608. for entry in response['feed']['entry']:
  609. index = entry['yt$position']['$t']
  610. if 'media$group' in entry and 'media$player' in entry['media$group']:
  611. videos.append((index, entry['media$group']['media$player']['url']))
  612. if len(response['feed']['entry']) < self._MAX_RESULTS:
  613. break
  614. page_num += 1
  615. videos = [v[1] for v in sorted(videos)]
  616. url_results = [self.url_result(url, 'Youtube') for url in videos]
  617. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  618. class YoutubeChannelIE(InfoExtractor):
  619. """Information Extractor for YouTube channels."""
  620. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  621. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  622. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  623. _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'
  624. IE_NAME = u'youtube:channel'
  625. def extract_videos_from_page(self, page):
  626. ids_in_page = []
  627. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  628. if mobj.group(1) not in ids_in_page:
  629. ids_in_page.append(mobj.group(1))
  630. return ids_in_page
  631. def _real_extract(self, url):
  632. # Extract channel id
  633. mobj = re.match(self._VALID_URL, url)
  634. if mobj is None:
  635. raise ExtractorError(u'Invalid URL: %s' % url)
  636. # Download channel page
  637. channel_id = mobj.group(1)
  638. video_ids = []
  639. pagenum = 1
  640. url = self._TEMPLATE_URL % (channel_id, pagenum)
  641. page = self._download_webpage(url, channel_id,
  642. u'Downloading page #%s' % pagenum)
  643. # Extract video identifiers
  644. ids_in_page = self.extract_videos_from_page(page)
  645. video_ids.extend(ids_in_page)
  646. # Download any subsequent channel pages using the json-based channel_ajax query
  647. if self._MORE_PAGES_INDICATOR in page:
  648. while True:
  649. pagenum = pagenum + 1
  650. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  651. page = self._download_webpage(url, channel_id,
  652. u'Downloading page #%s' % pagenum)
  653. page = json.loads(page)
  654. ids_in_page = self.extract_videos_from_page(page['content_html'])
  655. video_ids.extend(ids_in_page)
  656. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  657. break
  658. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  659. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  660. url_entries = [self.url_result(url, 'Youtube') for url in urls]
  661. return [self.playlist_result(url_entries, channel_id)]
  662. class YoutubeUserIE(InfoExtractor):
  663. """Information Extractor for YouTube users."""
  664. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  665. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  666. _GDATA_PAGE_SIZE = 50
  667. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  668. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  669. IE_NAME = u'youtube:user'
  670. def _real_extract(self, url):
  671. # Extract username
  672. mobj = re.match(self._VALID_URL, url)
  673. if mobj is None:
  674. raise ExtractorError(u'Invalid URL: %s' % url)
  675. username = mobj.group(1)
  676. # Download video ids using YouTube Data API. Result size per
  677. # query is limited (currently to 50 videos) so we need to query
  678. # page by page until there are no video ids - it means we got
  679. # all of them.
  680. video_ids = []
  681. pagenum = 0
  682. while True:
  683. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  684. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  685. page = self._download_webpage(gdata_url, username,
  686. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  687. # Extract video identifiers
  688. ids_in_page = []
  689. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  690. if mobj.group(1) not in ids_in_page:
  691. ids_in_page.append(mobj.group(1))
  692. video_ids.extend(ids_in_page)
  693. # A little optimization - if current page is not
  694. # "full", ie. does not contain PAGE_SIZE video ids then
  695. # we can assume that this page is the last one - there
  696. # are no more ids on further pages - no need to query
  697. # again.
  698. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  699. break
  700. pagenum += 1
  701. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  702. url_results = [self.url_result(url, 'Youtube') for url in urls]
  703. return [self.playlist_result(url_results, playlist_title = username)]
  704. class YoutubeSearchIE(SearchInfoExtractor):
  705. """Information Extractor for YouTube search queries."""
  706. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  707. _MAX_RESULTS = 1000
  708. IE_NAME = u'youtube:search'
  709. _SEARCH_KEY = 'ytsearch'
  710. def report_download_page(self, query, pagenum):
  711. """Report attempt to download search page with given number."""
  712. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  713. def _get_n_results(self, query, n):
  714. """Get a specified number of results for a query"""
  715. video_ids = []
  716. pagenum = 0
  717. limit = n
  718. while (50 * pagenum) < limit:
  719. self.report_download_page(query, pagenum+1)
  720. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  721. request = compat_urllib_request.Request(result_url)
  722. try:
  723. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  724. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  725. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  726. api_response = json.loads(data)['data']
  727. if not 'items' in api_response:
  728. raise ExtractorError(u'[youtube] No video results')
  729. new_ids = list(video['id'] for video in api_response['items'])
  730. video_ids += new_ids
  731. limit = min(n, api_response['totalItems'])
  732. pagenum += 1
  733. if len(video_ids) > n:
  734. video_ids = video_ids[:n]
  735. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  736. return self.playlist_result(videos, query)