youtube.py 35 KB

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