youtube.py 48 KB

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