youtube.py 49 KB

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