youtube.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. # coding: utf-8
  2. import json
  3. import netrc
  4. import re
  5. import socket
  6. import itertools
  7. from .common import InfoExtractor, SearchInfoExtractor
  8. from .subtitles import SubtitlesIE
  9. from ..utils import (
  10. compat_http_client,
  11. compat_parse_qs,
  12. compat_urllib_error,
  13. compat_urllib_parse,
  14. compat_urllib_request,
  15. compat_str,
  16. clean_html,
  17. get_element_by_id,
  18. ExtractorError,
  19. unescapeHTML,
  20. unified_strdate,
  21. orderedSet,
  22. )
  23. class YoutubeBaseInfoExtractor(InfoExtractor):
  24. """Provide base functions for Youtube extractors"""
  25. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  26. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  27. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  28. _NETRC_MACHINE = 'youtube'
  29. # If True it will raise an error if no login info is provided
  30. _LOGIN_REQUIRED = False
  31. def report_lang(self):
  32. """Report attempt to set language."""
  33. self.to_screen(u'Setting language')
  34. def _set_language(self):
  35. request = compat_urllib_request.Request(self._LANG_URL)
  36. try:
  37. self.report_lang()
  38. compat_urllib_request.urlopen(request).read()
  39. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  40. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  41. return False
  42. return True
  43. def _login(self):
  44. (username, password) = self._get_login_info()
  45. # No authentication to be performed
  46. if username is None:
  47. if self._LOGIN_REQUIRED:
  48. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  49. return False
  50. request = compat_urllib_request.Request(self._LOGIN_URL)
  51. try:
  52. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  53. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  54. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  55. return False
  56. galx = None
  57. dsh = None
  58. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  59. if match:
  60. galx = match.group(1)
  61. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  62. if match:
  63. dsh = match.group(1)
  64. # Log in
  65. login_form_strs = {
  66. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  67. u'Email': username,
  68. u'GALX': galx,
  69. u'Passwd': password,
  70. u'PersistentCookie': u'yes',
  71. u'_utf8': u'霱',
  72. u'bgresponse': u'js_disabled',
  73. u'checkConnection': u'',
  74. u'checkedDomains': u'youtube',
  75. u'dnConn': u'',
  76. u'dsh': dsh,
  77. u'pstMsg': u'0',
  78. u'rmShown': u'1',
  79. u'secTok': u'',
  80. u'signIn': u'Sign in',
  81. u'timeStmp': u'',
  82. u'service': u'youtube',
  83. u'uilel': u'3',
  84. u'hl': u'en_US',
  85. }
  86. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  87. # chokes on unicode
  88. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  89. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  90. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  91. try:
  92. self.report_login()
  93. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  94. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  95. self._downloader.report_warning(u'unable to log in: bad username or password')
  96. return False
  97. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  98. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  99. return False
  100. return True
  101. def _confirm_age(self):
  102. age_form = {
  103. 'next_url': '/',
  104. 'action_confirm': 'Confirm',
  105. }
  106. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  107. try:
  108. self.report_age_confirmation()
  109. compat_urllib_request.urlopen(request).read().decode('utf-8')
  110. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  111. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  112. return True
  113. def _real_initialize(self):
  114. if self._downloader is None:
  115. return
  116. if not self._set_language():
  117. return
  118. if not self._login():
  119. return
  120. self._confirm_age()
  121. class YoutubeSubtitlesIE(SubtitlesIE):
  122. def _get_available_subtitles(self, video_id):
  123. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  124. try:
  125. sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  126. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  127. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  128. return {}
  129. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  130. sub_lang_list = {}
  131. for l in lang_list:
  132. lang = l[1]
  133. params = compat_urllib_parse.urlencode({
  134. 'lang': lang,
  135. 'v': video_id,
  136. 'fmt': self._downloader.params.get('subtitlesformat'),
  137. })
  138. url = u'http://www.youtube.com/api/timedtext?' + params
  139. sub_lang_list[lang] = url
  140. if not sub_lang_list:
  141. self._downloader.report_warning(u'video doesn\'t have subtitles')
  142. return {}
  143. return sub_lang_list
  144. def _request_automatic_caption(self, video_id, webpage):
  145. """We need the webpage for getting the captions url, pass it as an
  146. argument to speed up the process."""
  147. sub_lang = (self._downloader.params.get('subtitleslangs') or ['en'])[0]
  148. sub_format = self._downloader.params.get('subtitlesformat')
  149. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  150. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  151. err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
  152. if mobj is None:
  153. self._downloader.report_warning(err_msg)
  154. return {}
  155. player_config = json.loads(mobj.group(1))
  156. try:
  157. args = player_config[u'args']
  158. caption_url = args[u'ttsurl']
  159. timestamp = args[u'timestamp']
  160. params = compat_urllib_parse.urlencode({
  161. 'lang': 'en',
  162. 'tlang': sub_lang,
  163. 'fmt': sub_format,
  164. 'ts': timestamp,
  165. 'kind': 'asr',
  166. })
  167. subtitles_url = caption_url + '&' + params
  168. sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
  169. return {sub_lang: sub}
  170. # An extractor error can be raise by the download process if there are
  171. # no automatic captions but there are subtitles
  172. except (KeyError, ExtractorError):
  173. self._downloader.report_warning(err_msg)
  174. return {}
  175. class YoutubeIE(YoutubeSubtitlesIE, YoutubeBaseInfoExtractor):
  176. IE_DESC = u'YouTube.com'
  177. _VALID_URL = r"""^
  178. (
  179. (?:https?://)? # http(s):// (optional)
  180. (?:(?:(?:(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  181. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  182. (?:.*?\#/)? # handle anchor (#/) redirect urls
  183. (?: # the various things that can precede the ID:
  184. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  185. |(?: # or the v= param in all its forms
  186. (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  187. (?:\?|\#!?) # the params delimiter ? or # or #!
  188. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  189. v=
  190. )
  191. ))
  192. |youtu\.be/ # just youtu.be/xxxx
  193. )
  194. )? # all until now is optional -> you can pass the naked ID
  195. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  196. (?(1).+)? # if we found the ID, everything can follow
  197. $"""
  198. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  199. # Listed in order of quality
  200. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '36', '17', '13',
  201. # Apple HTTP Live Streaming
  202. '96', '95', '94', '93', '92', '132', '151',
  203. # 3D
  204. '85', '84', '102', '83', '101', '82', '100',
  205. # Dash video
  206. '138', '137', '248', '136', '247', '135', '246',
  207. '245', '244', '134', '243', '133', '242', '160',
  208. # Dash audio
  209. '141', '172', '140', '171', '139',
  210. ]
  211. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '36', '17', '13',
  212. # Apple HTTP Live Streaming
  213. '96', '95', '94', '93', '92', '132', '151',
  214. # 3D
  215. '85', '102', '84', '101', '83', '100', '82',
  216. # Dash video
  217. '138', '248', '137', '247', '136', '246', '245',
  218. '244', '135', '243', '134', '242', '133', '160',
  219. # Dash audio
  220. '172', '141', '171', '140', '139',
  221. ]
  222. _video_formats_map = {
  223. 'flv': ['35', '34', '6', '5'],
  224. '3gp': ['36', '17', '13'],
  225. 'mp4': ['38', '37', '22', '18'],
  226. 'webm': ['46', '45', '44', '43'],
  227. }
  228. _video_extensions = {
  229. '13': '3gp',
  230. '17': '3gp',
  231. '18': 'mp4',
  232. '22': 'mp4',
  233. '36': '3gp',
  234. '37': 'mp4',
  235. '38': 'mp4',
  236. '43': 'webm',
  237. '44': 'webm',
  238. '45': 'webm',
  239. '46': 'webm',
  240. # 3d videos
  241. '82': 'mp4',
  242. '83': 'mp4',
  243. '84': 'mp4',
  244. '85': 'mp4',
  245. '100': 'webm',
  246. '101': 'webm',
  247. '102': 'webm',
  248. # Apple HTTP Live Streaming
  249. '92': 'mp4',
  250. '93': 'mp4',
  251. '94': 'mp4',
  252. '95': 'mp4',
  253. '96': 'mp4',
  254. '132': 'mp4',
  255. '151': 'mp4',
  256. # Dash mp4
  257. '133': 'mp4',
  258. '134': 'mp4',
  259. '135': 'mp4',
  260. '136': 'mp4',
  261. '137': 'mp4',
  262. '138': 'mp4',
  263. '139': 'mp4',
  264. '140': 'mp4',
  265. '141': 'mp4',
  266. '160': 'mp4',
  267. # Dash webm
  268. '171': 'webm',
  269. '172': 'webm',
  270. '242': 'webm',
  271. '243': 'webm',
  272. '244': 'webm',
  273. '245': 'webm',
  274. '246': 'webm',
  275. '247': 'webm',
  276. '248': 'webm',
  277. }
  278. _video_dimensions = {
  279. '5': '240x400',
  280. '6': '???',
  281. '13': '???',
  282. '17': '144x176',
  283. '18': '360x640',
  284. '22': '720x1280',
  285. '34': '360x640',
  286. '35': '480x854',
  287. '36': '240x320',
  288. '37': '1080x1920',
  289. '38': '3072x4096',
  290. '43': '360x640',
  291. '44': '480x854',
  292. '45': '720x1280',
  293. '46': '1080x1920',
  294. '82': '360p',
  295. '83': '480p',
  296. '84': '720p',
  297. '85': '1080p',
  298. '92': '240p',
  299. '93': '360p',
  300. '94': '480p',
  301. '95': '720p',
  302. '96': '1080p',
  303. '100': '360p',
  304. '101': '480p',
  305. '102': '720p',
  306. '132': '240p',
  307. '151': '72p',
  308. '133': '240p',
  309. '134': '360p',
  310. '135': '480p',
  311. '136': '720p',
  312. '137': '1080p',
  313. '138': '>1080p',
  314. '139': '48k',
  315. '140': '128k',
  316. '141': '256k',
  317. '160': '192p',
  318. '171': '128k',
  319. '172': '256k',
  320. '242': '240p',
  321. '243': '360p',
  322. '244': '480p',
  323. '245': '480p',
  324. '246': '480p',
  325. '247': '720p',
  326. '248': '1080p',
  327. }
  328. _special_itags = {
  329. '82': '3D',
  330. '83': '3D',
  331. '84': '3D',
  332. '85': '3D',
  333. '100': '3D',
  334. '101': '3D',
  335. '102': '3D',
  336. '133': 'DASH Video',
  337. '134': 'DASH Video',
  338. '135': 'DASH Video',
  339. '136': 'DASH Video',
  340. '137': 'DASH Video',
  341. '138': 'DASH Video',
  342. '139': 'DASH Audio',
  343. '140': 'DASH Audio',
  344. '141': 'DASH Audio',
  345. '160': 'DASH Video',
  346. '171': 'DASH Audio',
  347. '172': 'DASH Audio',
  348. '242': 'DASH Video',
  349. '243': 'DASH Video',
  350. '244': 'DASH Video',
  351. '245': 'DASH Video',
  352. '246': 'DASH Video',
  353. '247': 'DASH Video',
  354. '248': 'DASH Video',
  355. }
  356. IE_NAME = u'youtube'
  357. _TESTS = [
  358. {
  359. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  360. u"file": u"BaW_jenozKc.mp4",
  361. u"info_dict": {
  362. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  363. u"uploader": u"Philipp Hagemeister",
  364. u"uploader_id": u"phihag",
  365. u"upload_date": u"20121002",
  366. u"description": u"test chars: \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
  367. }
  368. },
  369. {
  370. u"url": u"http://www.youtube.com/watch?v=1ltcDfZMA3U",
  371. u"file": u"1ltcDfZMA3U.flv",
  372. u"note": u"Test VEVO video (#897)",
  373. u"info_dict": {
  374. u"upload_date": u"20070518",
  375. u"title": u"Maps - It Will Find You",
  376. u"description": u"Music video by Maps performing It Will Find You.",
  377. u"uploader": u"MuteUSA",
  378. u"uploader_id": u"MuteUSA"
  379. }
  380. },
  381. {
  382. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  383. u"file": u"UxxajLWwzqY.mp4",
  384. u"note": u"Test generic use_cipher_signature video (#897)",
  385. u"info_dict": {
  386. u"upload_date": u"20120506",
  387. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  388. u"description": u"md5:3e2666e0a55044490499ea45fe9037b7",
  389. u"uploader": u"Icona Pop",
  390. u"uploader_id": u"IconaPop"
  391. }
  392. },
  393. {
  394. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  395. u"file": u"07FYdnEawAQ.mp4",
  396. u"note": u"Test VEVO video with age protection (#956)",
  397. u"info_dict": {
  398. u"upload_date": u"20130703",
  399. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  400. u"description": u"md5:64249768eec3bc4276236606ea996373",
  401. u"uploader": u"justintimberlakeVEVO",
  402. u"uploader_id": u"justintimberlakeVEVO"
  403. }
  404. },
  405. {
  406. u'url': u'https://www.youtube.com/watch?v=TGi3HqYrWHE',
  407. u'file': u'TGi3HqYrWHE.mp4',
  408. u'note': u'm3u8 video',
  409. u'info_dict': {
  410. u'title': u'Triathlon - Men - London 2012 Olympic Games',
  411. u'description': u'- Men - TR02 - Triathlon - 07 August 2012 - London 2012 Olympic Games',
  412. u'uploader': u'olympic',
  413. u'upload_date': u'20120807',
  414. u'uploader_id': u'olympic',
  415. },
  416. u'params': {
  417. u'skip_download': True,
  418. },
  419. },
  420. ]
  421. @classmethod
  422. def suitable(cls, url):
  423. """Receives a URL and returns True if suitable for this IE."""
  424. if YoutubePlaylistIE.suitable(url): return False
  425. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  426. def report_video_webpage_download(self, video_id):
  427. """Report attempt to download video webpage."""
  428. self.to_screen(u'%s: Downloading video webpage' % video_id)
  429. def report_video_info_webpage_download(self, video_id):
  430. """Report attempt to download video info webpage."""
  431. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  432. def report_information_extraction(self, video_id):
  433. """Report attempt to extract video information."""
  434. self.to_screen(u'%s: Extracting video information' % video_id)
  435. def report_unavailable_format(self, video_id, format):
  436. """Report extracted video URL."""
  437. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  438. def report_rtmp_download(self):
  439. """Indicate the download will use the RTMP protocol."""
  440. self.to_screen(u'RTMP download detected')
  441. def _decrypt_signature(self, s):
  442. """Turn the encrypted s field into a working signature"""
  443. if len(s) == 92:
  444. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  445. elif len(s) == 90:
  446. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  447. elif len(s) == 89:
  448. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  449. elif len(s) == 88:
  450. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  451. elif len(s) == 87:
  452. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  453. elif len(s) == 86:
  454. return s[5:34] + s[0] + s[35:38] + s[3] + s[39:45] + s[38] + s[46:53] + s[73] + s[54:73] + s[85] + s[74:85] + s[53]
  455. elif len(s) == 85:
  456. return s[40] + s[82:43:-1] + s[22] + s[42:40:-1] + s[83] + s[39:22:-1] + s[0] + s[21:2:-1]
  457. elif len(s) == 84:
  458. return s[81:36:-1] + s[0] + s[35:2:-1]
  459. elif len(s) == 83:
  460. return s[81:64:-1] + s[82] + s[63:52:-1] + s[45] + s[51:45:-1] + s[1] + s[44:1:-1] + s[0]
  461. elif len(s) == 82:
  462. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:82]
  463. elif len(s) == 81:
  464. return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  465. elif len(s) == 80:
  466. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  467. elif len(s) == 79:
  468. return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  469. else:
  470. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  471. def _decrypt_signature_age_gate(self, s):
  472. # The videos with age protection use another player, so the algorithms
  473. # can be different.
  474. if len(s) == 86:
  475. return s[2:63] + s[82] + s[64:82] + s[63]
  476. else:
  477. # Fallback to the other algortihms
  478. return self._decrypt_signature(s)
  479. def _print_formats(self, formats):
  480. print('Available formats:')
  481. for x in formats:
  482. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  483. self._video_dimensions.get(x, '???'),
  484. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  485. def _extract_id(self, url):
  486. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  487. if mobj is None:
  488. raise ExtractorError(u'Invalid URL: %s' % url)
  489. video_id = mobj.group(2)
  490. return video_id
  491. def _get_video_url_list(self, url_map):
  492. """
  493. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  494. with the requested formats.
  495. """
  496. req_format = self._downloader.params.get('format', None)
  497. format_limit = self._downloader.params.get('format_limit', None)
  498. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  499. if format_limit is not None and format_limit in available_formats:
  500. format_list = available_formats[available_formats.index(format_limit):]
  501. else:
  502. format_list = available_formats
  503. existing_formats = [x for x in format_list if x in url_map]
  504. if len(existing_formats) == 0:
  505. raise ExtractorError(u'no known formats available for video')
  506. if self._downloader.params.get('listformats', None):
  507. self._print_formats(existing_formats)
  508. return
  509. if req_format is None or req_format == 'best':
  510. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  511. elif req_format == 'worst':
  512. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  513. elif req_format in ('-1', 'all'):
  514. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  515. else:
  516. # Specific formats. We pick the first in a slash-delimeted sequence.
  517. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  518. # available in the specified format. For example,
  519. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  520. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  521. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  522. req_formats = req_format.split('/')
  523. video_url_list = None
  524. for rf in req_formats:
  525. if rf in url_map:
  526. video_url_list = [(rf, url_map[rf])]
  527. break
  528. if rf in self._video_formats_map:
  529. for srf in self._video_formats_map[rf]:
  530. if srf in url_map:
  531. video_url_list = [(srf, url_map[srf])]
  532. break
  533. else:
  534. continue
  535. break
  536. if video_url_list is None:
  537. raise ExtractorError(u'requested format not available')
  538. return video_url_list
  539. def _extract_from_m3u8(self, manifest_url, video_id):
  540. url_map = {}
  541. def _get_urls(_manifest):
  542. lines = _manifest.split('\n')
  543. urls = filter(lambda l: l and not l.startswith('#'),
  544. lines)
  545. return urls
  546. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  547. formats_urls = _get_urls(manifest)
  548. for format_url in formats_urls:
  549. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  550. url_map[itag] = format_url
  551. return url_map
  552. def _real_extract(self, url):
  553. if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
  554. 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 ).')
  555. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  556. mobj = re.search(self._NEXT_URL_RE, url)
  557. if mobj:
  558. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  559. video_id = self._extract_id(url)
  560. # Get video webpage
  561. self.report_video_webpage_download(video_id)
  562. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  563. request = compat_urllib_request.Request(url)
  564. try:
  565. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  566. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  567. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  568. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  569. # Attempt to extract SWF player URL
  570. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  571. if mobj is not None:
  572. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  573. else:
  574. player_url = None
  575. # Get video info
  576. self.report_video_info_webpage_download(video_id)
  577. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  578. self.report_age_confirmation()
  579. age_gate = True
  580. # We simulate the access to the video from www.youtube.com/v/{video_id}
  581. # this can be viewed without login into Youtube
  582. data = compat_urllib_parse.urlencode({'video_id': video_id,
  583. 'el': 'embedded',
  584. 'gl': 'US',
  585. 'hl': 'en',
  586. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  587. 'asv': 3,
  588. 'sts':'1588',
  589. })
  590. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  591. video_info_webpage = self._download_webpage(video_info_url, video_id,
  592. note=False,
  593. errnote='unable to download video info webpage')
  594. video_info = compat_parse_qs(video_info_webpage)
  595. else:
  596. age_gate = False
  597. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  598. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  599. % (video_id, el_type))
  600. video_info_webpage = self._download_webpage(video_info_url, video_id,
  601. note=False,
  602. errnote='unable to download video info webpage')
  603. video_info = compat_parse_qs(video_info_webpage)
  604. if 'token' in video_info:
  605. break
  606. if 'token' not in video_info:
  607. if 'reason' in video_info:
  608. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  609. else:
  610. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  611. # Check for "rental" videos
  612. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  613. raise ExtractorError(u'"rental" videos not supported')
  614. # Start extracting information
  615. self.report_information_extraction(video_id)
  616. # uploader
  617. if 'author' not in video_info:
  618. raise ExtractorError(u'Unable to extract uploader name')
  619. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  620. # uploader_id
  621. video_uploader_id = None
  622. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  623. if mobj is not None:
  624. video_uploader_id = mobj.group(1)
  625. else:
  626. self._downloader.report_warning(u'unable to extract uploader nickname')
  627. # title
  628. if 'title' not in video_info:
  629. raise ExtractorError(u'Unable to extract video title')
  630. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  631. # thumbnail image
  632. # We try first to get a high quality image:
  633. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  634. video_webpage, re.DOTALL)
  635. if m_thumb is not None:
  636. video_thumbnail = m_thumb.group(1)
  637. elif 'thumbnail_url' not in video_info:
  638. self._downloader.report_warning(u'unable to extract video thumbnail')
  639. video_thumbnail = ''
  640. else: # don't panic if we can't find it
  641. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  642. # upload date
  643. upload_date = None
  644. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  645. if mobj is not None:
  646. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  647. upload_date = unified_strdate(upload_date)
  648. # description
  649. video_description = get_element_by_id("eow-description", video_webpage)
  650. if video_description:
  651. video_description = clean_html(video_description)
  652. else:
  653. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  654. if fd_mobj:
  655. video_description = unescapeHTML(fd_mobj.group(1))
  656. else:
  657. video_description = u''
  658. # subtitles
  659. video_subtitles = None
  660. if self._downloader.params.get('writesubtitles', False) or self._downloader.params.get('allsubtitles', False):
  661. video_subtitles = self._extract_subtitles(video_id)
  662. elif self._downloader.params.get('writeautomaticsub', False):
  663. video_subtitles = self._request_automatic_caption(video_id, video_webpage)
  664. if self._downloader.params.get('listsubtitles', False):
  665. self._list_available_subtitles(video_id)
  666. return
  667. if 'length_seconds' not in video_info:
  668. self._downloader.report_warning(u'unable to extract video duration')
  669. video_duration = ''
  670. else:
  671. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  672. # Decide which formats to download
  673. try:
  674. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  675. if not mobj:
  676. raise ValueError('Could not find vevo ID')
  677. info = json.loads(mobj.group(1))
  678. args = info['args']
  679. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  680. # this signatures are encrypted
  681. m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
  682. if m_s is not None:
  683. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  684. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  685. m_s = re.search(r'[&,]s=', args.get('adaptive_fmts', u''))
  686. if m_s is not None:
  687. if 'url_encoded_fmt_stream_map' in video_info:
  688. video_info['url_encoded_fmt_stream_map'][0] += ',' + args['adaptive_fmts']
  689. else:
  690. video_info['url_encoded_fmt_stream_map'] = [args['adaptive_fmts']]
  691. elif 'adaptive_fmts' in video_info:
  692. if 'url_encoded_fmt_stream_map' in video_info:
  693. video_info['url_encoded_fmt_stream_map'][0] += ',' + video_info['adaptive_fmts'][0]
  694. else:
  695. video_info['url_encoded_fmt_stream_map'] = video_info['adaptive_fmts']
  696. except ValueError:
  697. pass
  698. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  699. self.report_rtmp_download()
  700. video_url_list = [(None, video_info['conn'][0])]
  701. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  702. if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
  703. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  704. url_map = {}
  705. for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
  706. url_data = compat_parse_qs(url_data_str)
  707. if 'itag' in url_data and 'url' in url_data:
  708. url = url_data['url'][0]
  709. if 'sig' in url_data:
  710. url += '&signature=' + url_data['sig'][0]
  711. elif 's' in url_data:
  712. if self._downloader.params.get('verbose'):
  713. s = url_data['s'][0]
  714. if age_gate:
  715. player_version = self._search_regex(r'ad3-(.+?)\.swf',
  716. video_info['ad3_module'][0] if 'ad3_module' in video_info else 'NOT FOUND',
  717. 'flash player', fatal=False)
  718. player = 'flash player %s' % player_version
  719. else:
  720. player = u'html5 player %s' % self._search_regex(r'html5player-(.+?)\.js', video_webpage,
  721. 'html5 player', fatal=False)
  722. parts_sizes = u'.'.join(compat_str(len(part)) for part in s.split('.'))
  723. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  724. (len(s), parts_sizes, url_data['itag'][0], player))
  725. encrypted_sig = url_data['s'][0]
  726. if age_gate:
  727. signature = self._decrypt_signature_age_gate(encrypted_sig)
  728. else:
  729. signature = self._decrypt_signature(encrypted_sig)
  730. url += '&signature=' + signature
  731. if 'ratebypass' not in url:
  732. url += '&ratebypass=yes'
  733. url_map[url_data['itag'][0]] = url
  734. video_url_list = self._get_video_url_list(url_map)
  735. if not video_url_list:
  736. return
  737. elif video_info.get('hlsvp'):
  738. manifest_url = video_info['hlsvp'][0]
  739. url_map = self._extract_from_m3u8(manifest_url, video_id)
  740. video_url_list = self._get_video_url_list(url_map)
  741. if not video_url_list:
  742. return
  743. else:
  744. raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
  745. results = []
  746. for format_param, video_real_url in video_url_list:
  747. # Extension
  748. video_extension = self._video_extensions.get(format_param, 'flv')
  749. video_format = '{0} - {1}{2}'.format(format_param if format_param else video_extension,
  750. self._video_dimensions.get(format_param, '???'),
  751. ' ('+self._special_itags[format_param]+')' if format_param in self._special_itags else '')
  752. results.append({
  753. 'id': video_id,
  754. 'url': video_real_url,
  755. 'uploader': video_uploader,
  756. 'uploader_id': video_uploader_id,
  757. 'upload_date': upload_date,
  758. 'title': video_title,
  759. 'ext': video_extension,
  760. 'format': video_format,
  761. 'thumbnail': video_thumbnail,
  762. 'description': video_description,
  763. 'player_url': player_url,
  764. 'subtitles': video_subtitles,
  765. 'duration': video_duration
  766. })
  767. return results
  768. class YoutubePlaylistIE(InfoExtractor):
  769. IE_DESC = u'YouTube.com playlists'
  770. _VALID_URL = r"""(?:
  771. (?:https?://)?
  772. (?:\w+\.)?
  773. youtube\.com/
  774. (?:
  775. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  776. \? (?:.*?&)*? (?:p|a|list)=
  777. | p/
  778. )
  779. ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
  780. .*
  781. |
  782. ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
  783. )"""
  784. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
  785. _MAX_RESULTS = 50
  786. IE_NAME = u'youtube:playlist'
  787. @classmethod
  788. def suitable(cls, url):
  789. """Receives a URL and returns True if suitable for this IE."""
  790. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  791. def _real_extract(self, url):
  792. # Extract playlist id
  793. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  794. if mobj is None:
  795. raise ExtractorError(u'Invalid URL: %s' % url)
  796. # Download playlist videos from API
  797. playlist_id = mobj.group(1) or mobj.group(2)
  798. videos = []
  799. for page_num in itertools.count(1):
  800. start_index = self._MAX_RESULTS * (page_num - 1) + 1
  801. if start_index >= 1000:
  802. self._downloader.report_warning(u'Max number of results reached')
  803. break
  804. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, start_index)
  805. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  806. try:
  807. response = json.loads(page)
  808. except ValueError as err:
  809. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  810. if 'feed' not in response:
  811. raise ExtractorError(u'Got a malformed response from YouTube API')
  812. playlist_title = response['feed']['title']['$t']
  813. if 'entry' not in response['feed']:
  814. # Number of videos is a multiple of self._MAX_RESULTS
  815. break
  816. for entry in response['feed']['entry']:
  817. index = entry['yt$position']['$t']
  818. if 'media$group' in entry and 'yt$videoid' in entry['media$group']:
  819. videos.append((
  820. index,
  821. 'https://www.youtube.com/watch?v=' + entry['media$group']['yt$videoid']['$t']
  822. ))
  823. videos = [v[1] for v in sorted(videos)]
  824. url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
  825. return [self.playlist_result(url_results, playlist_id, playlist_title)]
  826. class YoutubeChannelIE(InfoExtractor):
  827. IE_DESC = u'YouTube.com channels'
  828. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  829. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  830. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  831. _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  832. IE_NAME = u'youtube:channel'
  833. def extract_videos_from_page(self, page):
  834. ids_in_page = []
  835. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  836. if mobj.group(1) not in ids_in_page:
  837. ids_in_page.append(mobj.group(1))
  838. return ids_in_page
  839. def _real_extract(self, url):
  840. # Extract channel id
  841. mobj = re.match(self._VALID_URL, url)
  842. if mobj is None:
  843. raise ExtractorError(u'Invalid URL: %s' % url)
  844. # Download channel page
  845. channel_id = mobj.group(1)
  846. video_ids = []
  847. pagenum = 1
  848. url = self._TEMPLATE_URL % (channel_id, pagenum)
  849. page = self._download_webpage(url, channel_id,
  850. u'Downloading page #%s' % pagenum)
  851. # Extract video identifiers
  852. ids_in_page = self.extract_videos_from_page(page)
  853. video_ids.extend(ids_in_page)
  854. # Download any subsequent channel pages using the json-based channel_ajax query
  855. if self._MORE_PAGES_INDICATOR in page:
  856. for pagenum in itertools.count(1):
  857. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  858. page = self._download_webpage(url, channel_id,
  859. u'Downloading page #%s' % pagenum)
  860. page = json.loads(page)
  861. ids_in_page = self.extract_videos_from_page(page['content_html'])
  862. video_ids.extend(ids_in_page)
  863. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  864. break
  865. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  866. urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
  867. url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
  868. return [self.playlist_result(url_entries, channel_id)]
  869. class YoutubeUserIE(InfoExtractor):
  870. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  871. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?)|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  872. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  873. _GDATA_PAGE_SIZE = 50
  874. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  875. IE_NAME = u'youtube:user'
  876. @classmethod
  877. def suitable(cls, url):
  878. # Don't return True if the url can be extracted with other youtube
  879. # extractor, the regex would is too permissive and it would match.
  880. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  881. if any(ie.suitable(url) for ie in other_ies): return False
  882. else: return super(YoutubeUserIE, cls).suitable(url)
  883. def _real_extract(self, url):
  884. # Extract username
  885. mobj = re.match(self._VALID_URL, url)
  886. if mobj is None:
  887. raise ExtractorError(u'Invalid URL: %s' % url)
  888. username = mobj.group(1)
  889. # Download video ids using YouTube Data API. Result size per
  890. # query is limited (currently to 50 videos) so we need to query
  891. # page by page until there are no video ids - it means we got
  892. # all of them.
  893. video_ids = []
  894. for pagenum in itertools.count(0):
  895. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  896. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  897. page = self._download_webpage(gdata_url, username,
  898. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  899. try:
  900. response = json.loads(page)
  901. except ValueError as err:
  902. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  903. # Extract video identifiers
  904. ids_in_page = []
  905. for entry in response['feed']['entry']:
  906. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  907. video_ids.extend(ids_in_page)
  908. # A little optimization - if current page is not
  909. # "full", ie. does not contain PAGE_SIZE video ids then
  910. # we can assume that this page is the last one - there
  911. # are no more ids on further pages - no need to query
  912. # again.
  913. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  914. break
  915. urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
  916. url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
  917. return [self.playlist_result(url_results, playlist_title = username)]
  918. class YoutubeSearchIE(SearchInfoExtractor):
  919. IE_DESC = u'YouTube.com searches'
  920. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  921. _MAX_RESULTS = 1000
  922. IE_NAME = u'youtube:search'
  923. _SEARCH_KEY = 'ytsearch'
  924. def report_download_page(self, query, pagenum):
  925. """Report attempt to download search page with given number."""
  926. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  927. def _get_n_results(self, query, n):
  928. """Get a specified number of results for a query"""
  929. video_ids = []
  930. pagenum = 0
  931. limit = n
  932. while (50 * pagenum) < limit:
  933. self.report_download_page(query, pagenum+1)
  934. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  935. request = compat_urllib_request.Request(result_url)
  936. try:
  937. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  938. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  939. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  940. api_response = json.loads(data)['data']
  941. if not 'items' in api_response:
  942. raise ExtractorError(u'[youtube] No video results')
  943. new_ids = list(video['id'] for video in api_response['items'])
  944. video_ids += new_ids
  945. limit = min(n, api_response['totalItems'])
  946. pagenum += 1
  947. if len(video_ids) > n:
  948. video_ids = video_ids[:n]
  949. videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
  950. return self.playlist_result(videos, query)
  951. class YoutubeShowIE(InfoExtractor):
  952. IE_DESC = u'YouTube.com (multi-season) shows'
  953. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  954. IE_NAME = u'youtube:show'
  955. def _real_extract(self, url):
  956. mobj = re.match(self._VALID_URL, url)
  957. show_name = mobj.group(1)
  958. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  959. # There's one playlist for each season of the show
  960. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  961. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  962. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  963. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  964. """
  965. Base class for extractors that fetch info from
  966. http://www.youtube.com/feed_ajax
  967. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  968. """
  969. _LOGIN_REQUIRED = True
  970. _PAGING_STEP = 30
  971. # use action_load_personal_feed instead of action_load_system_feed
  972. _PERSONAL_FEED = False
  973. @property
  974. def _FEED_TEMPLATE(self):
  975. action = 'action_load_system_feed'
  976. if self._PERSONAL_FEED:
  977. action = 'action_load_personal_feed'
  978. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  979. @property
  980. def IE_NAME(self):
  981. return u'youtube:%s' % self._FEED_NAME
  982. def _real_initialize(self):
  983. self._login()
  984. def _real_extract(self, url):
  985. feed_entries = []
  986. # The step argument is available only in 2.7 or higher
  987. for i in itertools.count(0):
  988. paging = i*self._PAGING_STEP
  989. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  990. u'%s feed' % self._FEED_NAME,
  991. u'Downloading page %s' % i)
  992. info = json.loads(info)
  993. feed_html = info['feed_html']
  994. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  995. ids = orderedSet(m.group(1) for m in m_ids)
  996. feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
  997. if info['paging'] is None:
  998. break
  999. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1000. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1001. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1002. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1003. _FEED_NAME = 'subscriptions'
  1004. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1005. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1006. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1007. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1008. _FEED_NAME = 'recommended'
  1009. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1010. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1011. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1012. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1013. _FEED_NAME = 'watch_later'
  1014. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1015. _PAGING_STEP = 100
  1016. _PERSONAL_FEED = True
  1017. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1018. IE_NAME = u'youtube:favorites'
  1019. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1020. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1021. _LOGIN_REQUIRED = True
  1022. def _real_extract(self, url):
  1023. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1024. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1025. return self.url_result(playlist_id, 'YoutubePlaylist')