youtube.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  1. # coding: utf-8
  2. import collections
  3. import errno
  4. import io
  5. import itertools
  6. import json
  7. import os.path
  8. import re
  9. import socket
  10. import string
  11. import struct
  12. import traceback
  13. import zlib
  14. from .common import InfoExtractor, SearchInfoExtractor
  15. from .subtitles import SubtitlesInfoExtractor
  16. from ..utils import (
  17. compat_chr,
  18. compat_http_client,
  19. compat_parse_qs,
  20. compat_urllib_error,
  21. compat_urllib_parse,
  22. compat_urllib_request,
  23. compat_urlparse,
  24. compat_str,
  25. clean_html,
  26. get_cachedir,
  27. get_element_by_id,
  28. ExtractorError,
  29. unescapeHTML,
  30. unified_strdate,
  31. orderedSet,
  32. write_json_file,
  33. )
  34. class YoutubeBaseInfoExtractor(InfoExtractor):
  35. """Provide base functions for Youtube extractors"""
  36. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  37. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  38. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  39. _NETRC_MACHINE = 'youtube'
  40. # If True it will raise an error if no login info is provided
  41. _LOGIN_REQUIRED = False
  42. def report_lang(self):
  43. """Report attempt to set language."""
  44. self.to_screen(u'Setting language')
  45. def _set_language(self):
  46. request = compat_urllib_request.Request(self._LANG_URL)
  47. try:
  48. self.report_lang()
  49. compat_urllib_request.urlopen(request).read()
  50. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  51. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  52. return False
  53. return True
  54. def _login(self):
  55. (username, password) = self._get_login_info()
  56. # No authentication to be performed
  57. if username is None:
  58. if self._LOGIN_REQUIRED:
  59. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  60. return False
  61. request = compat_urllib_request.Request(self._LOGIN_URL)
  62. try:
  63. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  64. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  65. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  66. return False
  67. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  68. login_page, u'Login GALX parameter')
  69. # Log in
  70. login_form_strs = {
  71. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  72. u'Email': username,
  73. u'GALX': galx,
  74. u'Passwd': password,
  75. u'PersistentCookie': u'yes',
  76. u'_utf8': u'霱',
  77. u'bgresponse': u'js_disabled',
  78. u'checkConnection': u'',
  79. u'checkedDomains': u'youtube',
  80. u'dnConn': u'',
  81. u'pstMsg': u'0',
  82. u'rmShown': u'1',
  83. u'secTok': u'',
  84. u'signIn': u'Sign in',
  85. u'timeStmp': u'',
  86. u'service': u'youtube',
  87. u'uilel': u'3',
  88. u'hl': u'en_US',
  89. }
  90. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  91. # chokes on unicode
  92. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  93. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  94. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  95. try:
  96. self.report_login()
  97. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  98. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  99. self._downloader.report_warning(u'unable to log in: bad username or password')
  100. return False
  101. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  102. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  103. return False
  104. return True
  105. def _confirm_age(self):
  106. age_form = {
  107. 'next_url': '/',
  108. 'action_confirm': 'Confirm',
  109. }
  110. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  111. try:
  112. self.report_age_confirmation()
  113. compat_urllib_request.urlopen(request).read().decode('utf-8')
  114. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  115. raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
  116. return True
  117. def _real_initialize(self):
  118. if self._downloader is None:
  119. return
  120. if not self._set_language():
  121. return
  122. if not self._login():
  123. return
  124. self._confirm_age()
  125. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  126. IE_DESC = u'YouTube.com'
  127. _VALID_URL = r"""(?x)^
  128. (
  129. (?:https?://|//)? # http(s):// or protocol-independent URL (optional)
  130. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  131. tube\.majestyc\.net/|
  132. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  133. (?:.*?\#/)? # handle anchor (#/) redirect urls
  134. (?: # the various things that can precede the ID:
  135. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  136. |(?: # or the v= param in all its forms
  137. (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  138. (?:\?|\#!?) # the params delimiter ? or # or #!
  139. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  140. v=
  141. )
  142. ))
  143. |youtu\.be/ # just youtu.be/xxxx
  144. )
  145. )? # all until now is optional -> you can pass the naked ID
  146. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  147. (?(1).+)? # if we found the ID, everything can follow
  148. $"""
  149. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  150. # Listed in order of quality
  151. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '36', '17', '13',
  152. # Apple HTTP Live Streaming
  153. '96', '95', '94', '93', '92', '132', '151',
  154. # 3D
  155. '85', '84', '102', '83', '101', '82', '100',
  156. # Dash video
  157. '138', '137', '248', '136', '247', '135', '246',
  158. '245', '244', '134', '243', '133', '242', '160',
  159. # Dash audio
  160. '141', '172', '140', '171', '139',
  161. ]
  162. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '36', '17', '13',
  163. # Apple HTTP Live Streaming
  164. '96', '95', '94', '93', '92', '132', '151',
  165. # 3D
  166. '85', '102', '84', '101', '83', '100', '82',
  167. # Dash video
  168. '138', '248', '137', '247', '136', '246', '245',
  169. '244', '135', '243', '134', '242', '133', '160',
  170. # Dash audio
  171. '172', '141', '171', '140', '139',
  172. ]
  173. _video_formats_map = {
  174. 'flv': ['35', '34', '6', '5'],
  175. '3gp': ['36', '17', '13'],
  176. 'mp4': ['38', '37', '22', '18'],
  177. 'webm': ['46', '45', '44', '43'],
  178. }
  179. _video_extensions = {
  180. '13': '3gp',
  181. '17': '3gp',
  182. '18': 'mp4',
  183. '22': 'mp4',
  184. '36': '3gp',
  185. '37': 'mp4',
  186. '38': 'mp4',
  187. '43': 'webm',
  188. '44': 'webm',
  189. '45': 'webm',
  190. '46': 'webm',
  191. # 3d videos
  192. '82': 'mp4',
  193. '83': 'mp4',
  194. '84': 'mp4',
  195. '85': 'mp4',
  196. '100': 'webm',
  197. '101': 'webm',
  198. '102': 'webm',
  199. # Apple HTTP Live Streaming
  200. '92': 'mp4',
  201. '93': 'mp4',
  202. '94': 'mp4',
  203. '95': 'mp4',
  204. '96': 'mp4',
  205. '132': 'mp4',
  206. '151': 'mp4',
  207. # Dash mp4
  208. '133': 'mp4',
  209. '134': 'mp4',
  210. '135': 'mp4',
  211. '136': 'mp4',
  212. '137': 'mp4',
  213. '138': 'mp4',
  214. '160': 'mp4',
  215. # Dash mp4 audio
  216. '139': 'm4a',
  217. '140': 'm4a',
  218. '141': 'm4a',
  219. # Dash webm
  220. '171': 'webm',
  221. '172': 'webm',
  222. '242': 'webm',
  223. '243': 'webm',
  224. '244': 'webm',
  225. '245': 'webm',
  226. '246': 'webm',
  227. '247': 'webm',
  228. '248': 'webm',
  229. }
  230. _video_dimensions = {
  231. '5': '400x240',
  232. '6': '???',
  233. '13': '???',
  234. '17': '176x144',
  235. '18': '640x360',
  236. '22': '1280x720',
  237. '34': '640x360',
  238. '35': '854x480',
  239. '36': '320x240',
  240. '37': '1920x1080',
  241. '38': '4096x3072',
  242. '43': '640x360',
  243. '44': '854x480',
  244. '45': '1280x720',
  245. '46': '1920x1080',
  246. '82': '360p',
  247. '83': '480p',
  248. '84': '720p',
  249. '85': '1080p',
  250. '92': '240p',
  251. '93': '360p',
  252. '94': '480p',
  253. '95': '720p',
  254. '96': '1080p',
  255. '100': '360p',
  256. '101': '480p',
  257. '102': '720p',
  258. '132': '240p',
  259. '151': '72p',
  260. '133': '240p',
  261. '134': '360p',
  262. '135': '480p',
  263. '136': '720p',
  264. '137': '1080p',
  265. '138': '>1080p',
  266. '139': '48k',
  267. '140': '128k',
  268. '141': '256k',
  269. '160': '192p',
  270. '171': '128k',
  271. '172': '256k',
  272. '242': '240p',
  273. '243': '360p',
  274. '244': '480p',
  275. '245': '480p',
  276. '246': '480p',
  277. '247': '720p',
  278. '248': '1080p',
  279. }
  280. _special_itags = {
  281. '82': '3D',
  282. '83': '3D',
  283. '84': '3D',
  284. '85': '3D',
  285. '100': '3D',
  286. '101': '3D',
  287. '102': '3D',
  288. '133': 'DASH Video',
  289. '134': 'DASH Video',
  290. '135': 'DASH Video',
  291. '136': 'DASH Video',
  292. '137': 'DASH Video',
  293. '138': 'DASH Video',
  294. '139': 'DASH Audio',
  295. '140': 'DASH Audio',
  296. '141': 'DASH Audio',
  297. '160': 'DASH Video',
  298. '171': 'DASH Audio',
  299. '172': 'DASH Audio',
  300. '242': 'DASH Video',
  301. '243': 'DASH Video',
  302. '244': 'DASH Video',
  303. '245': 'DASH Video',
  304. '246': 'DASH Video',
  305. '247': 'DASH Video',
  306. '248': 'DASH Video',
  307. }
  308. IE_NAME = u'youtube'
  309. _TESTS = [
  310. {
  311. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  312. u"file": u"BaW_jenozKc.mp4",
  313. u"info_dict": {
  314. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  315. u"uploader": u"Philipp Hagemeister",
  316. u"uploader_id": u"phihag",
  317. u"upload_date": u"20121002",
  318. u"description": u"test chars: \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
  319. }
  320. },
  321. {
  322. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  323. u"file": u"UxxajLWwzqY.mp4",
  324. u"note": u"Test generic use_cipher_signature video (#897)",
  325. u"info_dict": {
  326. u"upload_date": u"20120506",
  327. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  328. u"description": u"md5:5b292926389560516e384ac437c0ec07",
  329. u"uploader": u"Icona Pop",
  330. u"uploader_id": u"IconaPop"
  331. }
  332. },
  333. {
  334. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  335. u"file": u"07FYdnEawAQ.mp4",
  336. u"note": u"Test VEVO video with age protection (#956)",
  337. u"info_dict": {
  338. u"upload_date": u"20130703",
  339. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  340. u"description": u"md5:64249768eec3bc4276236606ea996373",
  341. u"uploader": u"justintimberlakeVEVO",
  342. u"uploader_id": u"justintimberlakeVEVO"
  343. }
  344. },
  345. {
  346. u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
  347. u"file": u"yZIXLfi8CZQ.mp4",
  348. u"note": u"Embed-only video (#1746)",
  349. u"info_dict": {
  350. u"upload_date": u"20120608",
  351. u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
  352. u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
  353. u"uploader": u"SET India",
  354. u"uploader_id": u"setindia"
  355. }
  356. },
  357. ]
  358. @classmethod
  359. def suitable(cls, url):
  360. """Receives a URL and returns True if suitable for this IE."""
  361. if YoutubePlaylistIE.suitable(url): return False
  362. return re.match(cls._VALID_URL, url) is not None
  363. def __init__(self, *args, **kwargs):
  364. super(YoutubeIE, self).__init__(*args, **kwargs)
  365. self._player_cache = {}
  366. def report_video_webpage_download(self, video_id):
  367. """Report attempt to download video webpage."""
  368. self.to_screen(u'%s: Downloading video webpage' % video_id)
  369. def report_video_info_webpage_download(self, video_id):
  370. """Report attempt to download video info webpage."""
  371. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  372. def report_information_extraction(self, video_id):
  373. """Report attempt to extract video information."""
  374. self.to_screen(u'%s: Extracting video information' % video_id)
  375. def report_unavailable_format(self, video_id, format):
  376. """Report extracted video URL."""
  377. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  378. def report_rtmp_download(self):
  379. """Indicate the download will use the RTMP protocol."""
  380. self.to_screen(u'RTMP download detected')
  381. def _extract_signature_function(self, video_id, player_url, slen):
  382. id_m = re.match(r'.*-(?P<id>[a-zA-Z0-9_-]+)\.(?P<ext>[a-z]+)$',
  383. player_url)
  384. player_type = id_m.group('ext')
  385. player_id = id_m.group('id')
  386. # Read from filesystem cache
  387. func_id = '%s_%s_%d' % (player_type, player_id, slen)
  388. assert os.path.basename(func_id) == func_id
  389. cache_dir = get_cachedir(self._downloader.params)
  390. cache_enabled = cache_dir is not None
  391. if cache_enabled:
  392. cache_fn = os.path.join(os.path.expanduser(cache_dir),
  393. u'youtube-sigfuncs',
  394. func_id + '.json')
  395. try:
  396. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  397. cache_spec = json.load(cachef)
  398. return lambda s: u''.join(s[i] for i in cache_spec)
  399. except IOError:
  400. pass # No cache available
  401. if player_type == 'js':
  402. code = self._download_webpage(
  403. player_url, video_id,
  404. note=u'Downloading %s player %s' % (player_type, player_id),
  405. errnote=u'Download of %s failed' % player_url)
  406. res = self._parse_sig_js(code)
  407. elif player_type == 'swf':
  408. urlh = self._request_webpage(
  409. player_url, video_id,
  410. note=u'Downloading %s player %s' % (player_type, player_id),
  411. errnote=u'Download of %s failed' % player_url)
  412. code = urlh.read()
  413. res = self._parse_sig_swf(code)
  414. else:
  415. assert False, 'Invalid player type %r' % player_type
  416. if cache_enabled:
  417. try:
  418. test_string = u''.join(map(compat_chr, range(slen)))
  419. cache_res = res(test_string)
  420. cache_spec = [ord(c) for c in cache_res]
  421. try:
  422. os.makedirs(os.path.dirname(cache_fn))
  423. except OSError as ose:
  424. if ose.errno != errno.EEXIST:
  425. raise
  426. write_json_file(cache_spec, cache_fn)
  427. except Exception:
  428. tb = traceback.format_exc()
  429. self._downloader.report_warning(
  430. u'Writing cache to %r failed: %s' % (cache_fn, tb))
  431. return res
  432. def _print_sig_code(self, func, slen):
  433. def gen_sig_code(idxs):
  434. def _genslice(start, end, step):
  435. starts = u'' if start == 0 else str(start)
  436. ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
  437. steps = u'' if step == 1 else (u':%d' % step)
  438. return u's[%s%s%s]' % (starts, ends, steps)
  439. step = None
  440. start = '(Never used)' # Quelch pyflakes warnings - start will be
  441. # set as soon as step is set
  442. for i, prev in zip(idxs[1:], idxs[:-1]):
  443. if step is not None:
  444. if i - prev == step:
  445. continue
  446. yield _genslice(start, prev, step)
  447. step = None
  448. continue
  449. if i - prev in [-1, 1]:
  450. step = i - prev
  451. start = prev
  452. continue
  453. else:
  454. yield u's[%d]' % prev
  455. if step is None:
  456. yield u's[%d]' % i
  457. else:
  458. yield _genslice(start, i, step)
  459. test_string = u''.join(map(compat_chr, range(slen)))
  460. cache_res = func(test_string)
  461. cache_spec = [ord(c) for c in cache_res]
  462. expr_code = u' + '.join(gen_sig_code(cache_spec))
  463. code = u'if len(s) == %d:\n return %s\n' % (slen, expr_code)
  464. self.to_screen(u'Extracted signature function:\n' + code)
  465. def _parse_sig_js(self, jscode):
  466. funcname = self._search_regex(
  467. r'signature=([a-zA-Z]+)', jscode,
  468. u'Initial JS player signature function name')
  469. functions = {}
  470. def argidx(varname):
  471. return string.lowercase.index(varname)
  472. def interpret_statement(stmt, local_vars, allow_recursion=20):
  473. if allow_recursion < 0:
  474. raise ExtractorError(u'Recursion limit reached')
  475. if stmt.startswith(u'var '):
  476. stmt = stmt[len(u'var '):]
  477. ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
  478. r'=(?P<expr>.*)$', stmt)
  479. if ass_m:
  480. if ass_m.groupdict().get('index'):
  481. def assign(val):
  482. lvar = local_vars[ass_m.group('out')]
  483. idx = interpret_expression(ass_m.group('index'),
  484. local_vars, allow_recursion)
  485. assert isinstance(idx, int)
  486. lvar[idx] = val
  487. return val
  488. expr = ass_m.group('expr')
  489. else:
  490. def assign(val):
  491. local_vars[ass_m.group('out')] = val
  492. return val
  493. expr = ass_m.group('expr')
  494. elif stmt.startswith(u'return '):
  495. assign = lambda v: v
  496. expr = stmt[len(u'return '):]
  497. else:
  498. raise ExtractorError(
  499. u'Cannot determine left side of statement in %r' % stmt)
  500. v = interpret_expression(expr, local_vars, allow_recursion)
  501. return assign(v)
  502. def interpret_expression(expr, local_vars, allow_recursion):
  503. if expr.isdigit():
  504. return int(expr)
  505. if expr.isalpha():
  506. return local_vars[expr]
  507. m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
  508. if m:
  509. member = m.group('member')
  510. val = local_vars[m.group('in')]
  511. if member == 'split("")':
  512. return list(val)
  513. if member == 'join("")':
  514. return u''.join(val)
  515. if member == 'length':
  516. return len(val)
  517. if member == 'reverse()':
  518. return val[::-1]
  519. slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
  520. if slice_m:
  521. idx = interpret_expression(
  522. slice_m.group('idx'), local_vars, allow_recursion-1)
  523. return val[idx:]
  524. m = re.match(
  525. r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
  526. if m:
  527. val = local_vars[m.group('in')]
  528. idx = interpret_expression(m.group('idx'), local_vars,
  529. allow_recursion-1)
  530. return val[idx]
  531. m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
  532. if m:
  533. a = interpret_expression(m.group('a'),
  534. local_vars, allow_recursion)
  535. b = interpret_expression(m.group('b'),
  536. local_vars, allow_recursion)
  537. return a % b
  538. m = re.match(
  539. r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
  540. if m:
  541. fname = m.group('func')
  542. if fname not in functions:
  543. functions[fname] = extract_function(fname)
  544. argvals = [int(v) if v.isdigit() else local_vars[v]
  545. for v in m.group('args').split(',')]
  546. return functions[fname](argvals)
  547. raise ExtractorError(u'Unsupported JS expression %r' % expr)
  548. def extract_function(funcname):
  549. func_m = re.search(
  550. r'function ' + re.escape(funcname) +
  551. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  552. jscode)
  553. argnames = func_m.group('args').split(',')
  554. def resf(args):
  555. local_vars = dict(zip(argnames, args))
  556. for stmt in func_m.group('code').split(';'):
  557. res = interpret_statement(stmt, local_vars)
  558. return res
  559. return resf
  560. initial_function = extract_function(funcname)
  561. return lambda s: initial_function([s])
  562. def _parse_sig_swf(self, file_contents):
  563. if file_contents[1:3] != b'WS':
  564. raise ExtractorError(
  565. u'Not an SWF file; header is %r' % file_contents[:3])
  566. if file_contents[:1] == b'C':
  567. content = zlib.decompress(file_contents[8:])
  568. else:
  569. raise NotImplementedError(u'Unsupported compression format %r' %
  570. file_contents[:1])
  571. def extract_tags(content):
  572. pos = 0
  573. while pos < len(content):
  574. header16 = struct.unpack('<H', content[pos:pos+2])[0]
  575. pos += 2
  576. tag_code = header16 >> 6
  577. tag_len = header16 & 0x3f
  578. if tag_len == 0x3f:
  579. tag_len = struct.unpack('<I', content[pos:pos+4])[0]
  580. pos += 4
  581. assert pos+tag_len <= len(content)
  582. yield (tag_code, content[pos:pos+tag_len])
  583. pos += tag_len
  584. code_tag = next(tag
  585. for tag_code, tag in extract_tags(content)
  586. if tag_code == 82)
  587. p = code_tag.index(b'\0', 4) + 1
  588. code_reader = io.BytesIO(code_tag[p:])
  589. # Parse ABC (AVM2 ByteCode)
  590. def read_int(reader=None):
  591. if reader is None:
  592. reader = code_reader
  593. res = 0
  594. shift = 0
  595. for _ in range(5):
  596. buf = reader.read(1)
  597. assert len(buf) == 1
  598. b = struct.unpack('<B', buf)[0]
  599. res = res | ((b & 0x7f) << shift)
  600. if b & 0x80 == 0:
  601. break
  602. shift += 7
  603. return res
  604. def u30(reader=None):
  605. res = read_int(reader)
  606. assert res & 0xf0000000 == 0
  607. return res
  608. u32 = read_int
  609. def s32(reader=None):
  610. v = read_int(reader)
  611. if v & 0x80000000 != 0:
  612. v = - ((v ^ 0xffffffff) + 1)
  613. return v
  614. def read_string(reader=None):
  615. if reader is None:
  616. reader = code_reader
  617. slen = u30(reader)
  618. resb = reader.read(slen)
  619. assert len(resb) == slen
  620. return resb.decode('utf-8')
  621. def read_bytes(count, reader=None):
  622. if reader is None:
  623. reader = code_reader
  624. resb = reader.read(count)
  625. assert len(resb) == count
  626. return resb
  627. def read_byte(reader=None):
  628. resb = read_bytes(1, reader=reader)
  629. res = struct.unpack('<B', resb)[0]
  630. return res
  631. # minor_version + major_version
  632. read_bytes(2 + 2)
  633. # Constant pool
  634. int_count = u30()
  635. for _c in range(1, int_count):
  636. s32()
  637. uint_count = u30()
  638. for _c in range(1, uint_count):
  639. u32()
  640. double_count = u30()
  641. read_bytes((double_count-1) * 8)
  642. string_count = u30()
  643. constant_strings = [u'']
  644. for _c in range(1, string_count):
  645. s = read_string()
  646. constant_strings.append(s)
  647. namespace_count = u30()
  648. for _c in range(1, namespace_count):
  649. read_bytes(1) # kind
  650. u30() # name
  651. ns_set_count = u30()
  652. for _c in range(1, ns_set_count):
  653. count = u30()
  654. for _c2 in range(count):
  655. u30()
  656. multiname_count = u30()
  657. MULTINAME_SIZES = {
  658. 0x07: 2, # QName
  659. 0x0d: 2, # QNameA
  660. 0x0f: 1, # RTQName
  661. 0x10: 1, # RTQNameA
  662. 0x11: 0, # RTQNameL
  663. 0x12: 0, # RTQNameLA
  664. 0x09: 2, # Multiname
  665. 0x0e: 2, # MultinameA
  666. 0x1b: 1, # MultinameL
  667. 0x1c: 1, # MultinameLA
  668. }
  669. multinames = [u'']
  670. for _c in range(1, multiname_count):
  671. kind = u30()
  672. assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
  673. if kind == 0x07:
  674. u30() # namespace_idx
  675. name_idx = u30()
  676. multinames.append(constant_strings[name_idx])
  677. else:
  678. multinames.append('[MULTINAME kind: %d]' % kind)
  679. for _c2 in range(MULTINAME_SIZES[kind]):
  680. u30()
  681. # Methods
  682. method_count = u30()
  683. MethodInfo = collections.namedtuple(
  684. 'MethodInfo',
  685. ['NEED_ARGUMENTS', 'NEED_REST'])
  686. method_infos = []
  687. for method_id in range(method_count):
  688. param_count = u30()
  689. u30() # return type
  690. for _ in range(param_count):
  691. u30() # param type
  692. u30() # name index (always 0 for youtube)
  693. flags = read_byte()
  694. if flags & 0x08 != 0:
  695. # Options present
  696. option_count = u30()
  697. for c in range(option_count):
  698. u30() # val
  699. read_bytes(1) # kind
  700. if flags & 0x80 != 0:
  701. # Param names present
  702. for _ in range(param_count):
  703. u30() # param name
  704. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  705. method_infos.append(mi)
  706. # Metadata
  707. metadata_count = u30()
  708. for _c in range(metadata_count):
  709. u30() # name
  710. item_count = u30()
  711. for _c2 in range(item_count):
  712. u30() # key
  713. u30() # value
  714. def parse_traits_info():
  715. trait_name_idx = u30()
  716. kind_full = read_byte()
  717. kind = kind_full & 0x0f
  718. attrs = kind_full >> 4
  719. methods = {}
  720. if kind in [0x00, 0x06]: # Slot or Const
  721. u30() # Slot id
  722. u30() # type_name_idx
  723. vindex = u30()
  724. if vindex != 0:
  725. read_byte() # vkind
  726. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  727. u30() # disp_id
  728. method_idx = u30()
  729. methods[multinames[trait_name_idx]] = method_idx
  730. elif kind == 0x04: # Class
  731. u30() # slot_id
  732. u30() # classi
  733. elif kind == 0x05: # Function
  734. u30() # slot_id
  735. function_idx = u30()
  736. methods[function_idx] = multinames[trait_name_idx]
  737. else:
  738. raise ExtractorError(u'Unsupported trait kind %d' % kind)
  739. if attrs & 0x4 != 0: # Metadata present
  740. metadata_count = u30()
  741. for _c3 in range(metadata_count):
  742. u30() # metadata index
  743. return methods
  744. # Classes
  745. TARGET_CLASSNAME = u'SignatureDecipher'
  746. searched_idx = multinames.index(TARGET_CLASSNAME)
  747. searched_class_id = None
  748. class_count = u30()
  749. for class_id in range(class_count):
  750. name_idx = u30()
  751. if name_idx == searched_idx:
  752. # We found the class we're looking for!
  753. searched_class_id = class_id
  754. u30() # super_name idx
  755. flags = read_byte()
  756. if flags & 0x08 != 0: # Protected namespace is present
  757. u30() # protected_ns_idx
  758. intrf_count = u30()
  759. for _c2 in range(intrf_count):
  760. u30()
  761. u30() # iinit
  762. trait_count = u30()
  763. for _c2 in range(trait_count):
  764. parse_traits_info()
  765. if searched_class_id is None:
  766. raise ExtractorError(u'Target class %r not found' %
  767. TARGET_CLASSNAME)
  768. method_names = {}
  769. method_idxs = {}
  770. for class_id in range(class_count):
  771. u30() # cinit
  772. trait_count = u30()
  773. for _c2 in range(trait_count):
  774. trait_methods = parse_traits_info()
  775. if class_id == searched_class_id:
  776. method_names.update(trait_methods.items())
  777. method_idxs.update(dict(
  778. (idx, name)
  779. for name, idx in trait_methods.items()))
  780. # Scripts
  781. script_count = u30()
  782. for _c in range(script_count):
  783. u30() # init
  784. trait_count = u30()
  785. for _c2 in range(trait_count):
  786. parse_traits_info()
  787. # Method bodies
  788. method_body_count = u30()
  789. Method = collections.namedtuple('Method', ['code', 'local_count'])
  790. methods = {}
  791. for _c in range(method_body_count):
  792. method_idx = u30()
  793. u30() # max_stack
  794. local_count = u30()
  795. u30() # init_scope_depth
  796. u30() # max_scope_depth
  797. code_length = u30()
  798. code = read_bytes(code_length)
  799. if method_idx in method_idxs:
  800. m = Method(code, local_count)
  801. methods[method_idxs[method_idx]] = m
  802. exception_count = u30()
  803. for _c2 in range(exception_count):
  804. u30() # from
  805. u30() # to
  806. u30() # target
  807. u30() # exc_type
  808. u30() # var_name
  809. trait_count = u30()
  810. for _c2 in range(trait_count):
  811. parse_traits_info()
  812. assert p + code_reader.tell() == len(code_tag)
  813. assert len(methods) == len(method_idxs)
  814. method_pyfunctions = {}
  815. def extract_function(func_name):
  816. if func_name in method_pyfunctions:
  817. return method_pyfunctions[func_name]
  818. if func_name not in methods:
  819. raise ExtractorError(u'Cannot find function %r' % func_name)
  820. m = methods[func_name]
  821. def resfunc(args):
  822. registers = ['(this)'] + list(args) + [None] * m.local_count
  823. stack = []
  824. coder = io.BytesIO(m.code)
  825. while True:
  826. opcode = struct.unpack('!B', coder.read(1))[0]
  827. if opcode == 36: # pushbyte
  828. v = struct.unpack('!B', coder.read(1))[0]
  829. stack.append(v)
  830. elif opcode == 44: # pushstring
  831. idx = u30(coder)
  832. stack.append(constant_strings[idx])
  833. elif opcode == 48: # pushscope
  834. # We don't implement the scope register, so we'll just
  835. # ignore the popped value
  836. stack.pop()
  837. elif opcode == 70: # callproperty
  838. index = u30(coder)
  839. mname = multinames[index]
  840. arg_count = u30(coder)
  841. args = list(reversed(
  842. [stack.pop() for _ in range(arg_count)]))
  843. obj = stack.pop()
  844. if mname == u'split':
  845. assert len(args) == 1
  846. assert isinstance(args[0], compat_str)
  847. assert isinstance(obj, compat_str)
  848. if args[0] == u'':
  849. res = list(obj)
  850. else:
  851. res = obj.split(args[0])
  852. stack.append(res)
  853. elif mname == u'slice':
  854. assert len(args) == 1
  855. assert isinstance(args[0], int)
  856. assert isinstance(obj, list)
  857. res = obj[args[0]:]
  858. stack.append(res)
  859. elif mname == u'join':
  860. assert len(args) == 1
  861. assert isinstance(args[0], compat_str)
  862. assert isinstance(obj, list)
  863. res = args[0].join(obj)
  864. stack.append(res)
  865. elif mname in method_pyfunctions:
  866. stack.append(method_pyfunctions[mname](args))
  867. else:
  868. raise NotImplementedError(
  869. u'Unsupported property %r on %r'
  870. % (mname, obj))
  871. elif opcode == 72: # returnvalue
  872. res = stack.pop()
  873. return res
  874. elif opcode == 79: # callpropvoid
  875. index = u30(coder)
  876. mname = multinames[index]
  877. arg_count = u30(coder)
  878. args = list(reversed(
  879. [stack.pop() for _ in range(arg_count)]))
  880. obj = stack.pop()
  881. if mname == u'reverse':
  882. assert isinstance(obj, list)
  883. obj.reverse()
  884. else:
  885. raise NotImplementedError(
  886. u'Unsupported (void) property %r on %r'
  887. % (mname, obj))
  888. elif opcode == 93: # findpropstrict
  889. index = u30(coder)
  890. mname = multinames[index]
  891. res = extract_function(mname)
  892. stack.append(res)
  893. elif opcode == 97: # setproperty
  894. index = u30(coder)
  895. value = stack.pop()
  896. idx = stack.pop()
  897. obj = stack.pop()
  898. assert isinstance(obj, list)
  899. assert isinstance(idx, int)
  900. obj[idx] = value
  901. elif opcode == 98: # getlocal
  902. index = u30(coder)
  903. stack.append(registers[index])
  904. elif opcode == 99: # setlocal
  905. index = u30(coder)
  906. value = stack.pop()
  907. registers[index] = value
  908. elif opcode == 102: # getproperty
  909. index = u30(coder)
  910. pname = multinames[index]
  911. if pname == u'length':
  912. obj = stack.pop()
  913. assert isinstance(obj, list)
  914. stack.append(len(obj))
  915. else: # Assume attribute access
  916. idx = stack.pop()
  917. assert isinstance(idx, int)
  918. obj = stack.pop()
  919. assert isinstance(obj, list)
  920. stack.append(obj[idx])
  921. elif opcode == 128: # coerce
  922. u30(coder)
  923. elif opcode == 133: # coerce_s
  924. assert isinstance(stack[-1], (type(None), compat_str))
  925. elif opcode == 164: # modulo
  926. value2 = stack.pop()
  927. value1 = stack.pop()
  928. res = value1 % value2
  929. stack.append(res)
  930. elif opcode == 208: # getlocal_0
  931. stack.append(registers[0])
  932. elif opcode == 209: # getlocal_1
  933. stack.append(registers[1])
  934. elif opcode == 210: # getlocal_2
  935. stack.append(registers[2])
  936. elif opcode == 211: # getlocal_3
  937. stack.append(registers[3])
  938. elif opcode == 214: # setlocal_2
  939. registers[2] = stack.pop()
  940. elif opcode == 215: # setlocal_3
  941. registers[3] = stack.pop()
  942. else:
  943. raise NotImplementedError(
  944. u'Unsupported opcode %d' % opcode)
  945. method_pyfunctions[func_name] = resfunc
  946. return resfunc
  947. initial_function = extract_function(u'decipher')
  948. return lambda s: initial_function([s])
  949. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  950. """Turn the encrypted s field into a working signature"""
  951. if player_url is not None:
  952. if player_url.startswith(u'//'):
  953. player_url = u'https:' + player_url
  954. try:
  955. player_id = (player_url, len(s))
  956. if player_id not in self._player_cache:
  957. func = self._extract_signature_function(
  958. video_id, player_url, len(s)
  959. )
  960. self._player_cache[player_id] = func
  961. func = self._player_cache[player_id]
  962. if self._downloader.params.get('youtube_print_sig_code'):
  963. self._print_sig_code(func, len(s))
  964. return func(s)
  965. except Exception:
  966. tb = traceback.format_exc()
  967. self._downloader.report_warning(
  968. u'Automatic signature extraction failed: ' + tb)
  969. self._downloader.report_warning(
  970. u'Warning: Falling back to static signature algorithm')
  971. return self._static_decrypt_signature(
  972. s, video_id, player_url, age_gate)
  973. def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
  974. if age_gate:
  975. # The videos with age protection use another player, so the
  976. # algorithms can be different.
  977. if len(s) == 86:
  978. return s[2:63] + s[82] + s[64:82] + s[63]
  979. if len(s) == 93:
  980. return s[86:29:-1] + s[88] + s[28:5:-1]
  981. elif len(s) == 92:
  982. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  983. elif len(s) == 91:
  984. return s[84:27:-1] + s[86] + s[26:5:-1]
  985. elif len(s) == 90:
  986. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  987. elif len(s) == 89:
  988. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  989. elif len(s) == 88:
  990. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  991. elif len(s) == 87:
  992. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  993. elif len(s) == 86:
  994. return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
  995. elif len(s) == 85:
  996. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  997. elif len(s) == 84:
  998. return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
  999. elif len(s) == 83:
  1000. return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
  1001. elif len(s) == 82:
  1002. return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
  1003. elif len(s) == 81:
  1004. 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]
  1005. elif len(s) == 80:
  1006. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  1007. elif len(s) == 79:
  1008. 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]
  1009. else:
  1010. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  1011. def _get_available_subtitles(self, video_id, webpage):
  1012. try:
  1013. sub_list = self._download_webpage(
  1014. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1015. video_id, note=False)
  1016. except ExtractorError as err:
  1017. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  1018. return {}
  1019. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  1020. sub_lang_list = {}
  1021. for l in lang_list:
  1022. lang = l[1]
  1023. params = compat_urllib_parse.urlencode({
  1024. 'lang': lang,
  1025. 'v': video_id,
  1026. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  1027. 'name': l[0].encode('utf-8'),
  1028. })
  1029. url = u'http://www.youtube.com/api/timedtext?' + params
  1030. sub_lang_list[lang] = url
  1031. if not sub_lang_list:
  1032. self._downloader.report_warning(u'video doesn\'t have subtitles')
  1033. return {}
  1034. return sub_lang_list
  1035. def _get_available_automatic_caption(self, video_id, webpage):
  1036. """We need the webpage for getting the captions url, pass it as an
  1037. argument to speed up the process."""
  1038. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  1039. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  1040. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  1041. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  1042. if mobj is None:
  1043. self._downloader.report_warning(err_msg)
  1044. return {}
  1045. player_config = json.loads(mobj.group(1))
  1046. try:
  1047. args = player_config[u'args']
  1048. caption_url = args[u'ttsurl']
  1049. timestamp = args[u'timestamp']
  1050. # We get the available subtitles
  1051. list_params = compat_urllib_parse.urlencode({
  1052. 'type': 'list',
  1053. 'tlangs': 1,
  1054. 'asrs': 1,
  1055. })
  1056. list_url = caption_url + '&' + list_params
  1057. caption_list = self._download_xml(list_url, video_id)
  1058. original_lang_node = caption_list.find('track')
  1059. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  1060. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  1061. return {}
  1062. original_lang = original_lang_node.attrib['lang_code']
  1063. sub_lang_list = {}
  1064. for lang_node in caption_list.findall('target'):
  1065. sub_lang = lang_node.attrib['lang_code']
  1066. params = compat_urllib_parse.urlencode({
  1067. 'lang': original_lang,
  1068. 'tlang': sub_lang,
  1069. 'fmt': sub_format,
  1070. 'ts': timestamp,
  1071. 'kind': 'asr',
  1072. })
  1073. sub_lang_list[sub_lang] = caption_url + '&' + params
  1074. return sub_lang_list
  1075. # An extractor error can be raise by the download process if there are
  1076. # no automatic captions but there are subtitles
  1077. except (KeyError, ExtractorError):
  1078. self._downloader.report_warning(err_msg)
  1079. return {}
  1080. def _print_formats(self, formats):
  1081. print('Available formats:')
  1082. for x in formats:
  1083. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  1084. self._video_dimensions.get(x, '???'),
  1085. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  1086. def _extract_id(self, url):
  1087. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1088. if mobj is None:
  1089. raise ExtractorError(u'Invalid URL: %s' % url)
  1090. video_id = mobj.group(2)
  1091. return video_id
  1092. def _get_video_url_list(self, url_map):
  1093. """
  1094. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  1095. with the requested formats.
  1096. """
  1097. req_format = self._downloader.params.get('format', None)
  1098. format_limit = self._downloader.params.get('format_limit', None)
  1099. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  1100. if format_limit is not None and format_limit in available_formats:
  1101. format_list = available_formats[available_formats.index(format_limit):]
  1102. else:
  1103. format_list = available_formats
  1104. existing_formats = [x for x in format_list if x in url_map]
  1105. if len(existing_formats) == 0:
  1106. raise ExtractorError(u'no known formats available for video')
  1107. if self._downloader.params.get('listformats', None):
  1108. self._print_formats(existing_formats)
  1109. return
  1110. if req_format is None or req_format == 'best':
  1111. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1112. elif req_format == 'worst':
  1113. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  1114. elif req_format in ('-1', 'all'):
  1115. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1116. else:
  1117. # Specific formats. We pick the first in a slash-delimeted sequence.
  1118. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  1119. # available in the specified format. For example,
  1120. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1121. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  1122. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  1123. req_formats = req_format.split('/')
  1124. video_url_list = None
  1125. for rf in req_formats:
  1126. if rf in url_map:
  1127. video_url_list = [(rf, url_map[rf])]
  1128. break
  1129. if rf in self._video_formats_map:
  1130. for srf in self._video_formats_map[rf]:
  1131. if srf in url_map:
  1132. video_url_list = [(srf, url_map[srf])]
  1133. break
  1134. else:
  1135. continue
  1136. break
  1137. if video_url_list is None:
  1138. raise ExtractorError(u'requested format not available')
  1139. return video_url_list
  1140. def _extract_from_m3u8(self, manifest_url, video_id):
  1141. url_map = {}
  1142. def _get_urls(_manifest):
  1143. lines = _manifest.split('\n')
  1144. urls = filter(lambda l: l and not l.startswith('#'),
  1145. lines)
  1146. return urls
  1147. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  1148. formats_urls = _get_urls(manifest)
  1149. for format_url in formats_urls:
  1150. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1151. url_map[itag] = format_url
  1152. return url_map
  1153. def _extract_annotations(self, video_id):
  1154. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  1155. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  1156. def _real_extract(self, url):
  1157. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1158. mobj = re.search(self._NEXT_URL_RE, url)
  1159. if mobj:
  1160. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  1161. video_id = self._extract_id(url)
  1162. # Get video webpage
  1163. self.report_video_webpage_download(video_id)
  1164. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  1165. request = compat_urllib_request.Request(url)
  1166. try:
  1167. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  1168. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1169. raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
  1170. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  1171. # Attempt to extract SWF player URL
  1172. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1173. if mobj is not None:
  1174. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1175. else:
  1176. player_url = None
  1177. # Get video info
  1178. self.report_video_info_webpage_download(video_id)
  1179. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1180. self.report_age_confirmation()
  1181. age_gate = True
  1182. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1183. # this can be viewed without login into Youtube
  1184. data = compat_urllib_parse.urlencode({'video_id': video_id,
  1185. 'el': 'player_embedded',
  1186. 'gl': 'US',
  1187. 'hl': 'en',
  1188. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1189. 'asv': 3,
  1190. 'sts':'1588',
  1191. })
  1192. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  1193. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1194. note=False,
  1195. errnote='unable to download video info webpage')
  1196. video_info = compat_parse_qs(video_info_webpage)
  1197. else:
  1198. age_gate = False
  1199. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1200. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1201. % (video_id, el_type))
  1202. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1203. note=False,
  1204. errnote='unable to download video info webpage')
  1205. video_info = compat_parse_qs(video_info_webpage)
  1206. if 'token' in video_info:
  1207. break
  1208. if 'token' not in video_info:
  1209. if 'reason' in video_info:
  1210. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  1211. else:
  1212. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  1213. if 'view_count' in video_info:
  1214. view_count = int(video_info['view_count'][0])
  1215. else:
  1216. view_count = None
  1217. # Check for "rental" videos
  1218. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1219. raise ExtractorError(u'"rental" videos not supported')
  1220. # Start extracting information
  1221. self.report_information_extraction(video_id)
  1222. # uploader
  1223. if 'author' not in video_info:
  1224. raise ExtractorError(u'Unable to extract uploader name')
  1225. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1226. # uploader_id
  1227. video_uploader_id = None
  1228. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1229. if mobj is not None:
  1230. video_uploader_id = mobj.group(1)
  1231. else:
  1232. self._downloader.report_warning(u'unable to extract uploader nickname')
  1233. # title
  1234. if 'title' in video_info:
  1235. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  1236. else:
  1237. self._downloader.report_warning(u'Unable to extract video title')
  1238. video_title = u'_'
  1239. # thumbnail image
  1240. # We try first to get a high quality image:
  1241. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1242. video_webpage, re.DOTALL)
  1243. if m_thumb is not None:
  1244. video_thumbnail = m_thumb.group(1)
  1245. elif 'thumbnail_url' not in video_info:
  1246. self._downloader.report_warning(u'unable to extract video thumbnail')
  1247. video_thumbnail = None
  1248. else: # don't panic if we can't find it
  1249. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1250. # upload date
  1251. upload_date = None
  1252. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1253. if mobj is not None:
  1254. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1255. upload_date = unified_strdate(upload_date)
  1256. # description
  1257. video_description = get_element_by_id("eow-description", video_webpage)
  1258. if video_description:
  1259. video_description = clean_html(video_description)
  1260. else:
  1261. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1262. if fd_mobj:
  1263. video_description = unescapeHTML(fd_mobj.group(1))
  1264. else:
  1265. video_description = u''
  1266. # subtitles
  1267. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1268. if self._downloader.params.get('listsubtitles', False):
  1269. self._list_available_subtitles(video_id, video_webpage)
  1270. return
  1271. if 'length_seconds' not in video_info:
  1272. self._downloader.report_warning(u'unable to extract video duration')
  1273. video_duration = ''
  1274. else:
  1275. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  1276. # annotations
  1277. video_annotations = None
  1278. if self._downloader.params.get('writeannotations', False):
  1279. video_annotations = self._extract_annotations(video_id)
  1280. # Decide which formats to download
  1281. try:
  1282. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  1283. if not mobj:
  1284. raise ValueError('Could not find vevo ID')
  1285. info = json.loads(mobj.group(1))
  1286. args = info['args']
  1287. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1288. # this signatures are encrypted
  1289. if 'url_encoded_fmt_stream_map' not in args:
  1290. raise ValueError(u'No stream_map present') # caught below
  1291. re_signature = re.compile(r'[&,]s=')
  1292. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  1293. if m_s is not None:
  1294. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1295. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1296. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  1297. if m_s is not None:
  1298. if 'adaptive_fmts' in video_info:
  1299. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  1300. else:
  1301. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  1302. except ValueError:
  1303. pass
  1304. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1305. self.report_rtmp_download()
  1306. video_url_list = [(None, video_info['conn'][0])]
  1307. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  1308. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  1309. if 'rtmpe%3Dyes' in encoded_url_map:
  1310. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1311. url_map = {}
  1312. for url_data_str in encoded_url_map.split(','):
  1313. url_data = compat_parse_qs(url_data_str)
  1314. if 'itag' in url_data and 'url' in url_data:
  1315. url = url_data['url'][0]
  1316. if 'sig' in url_data:
  1317. url += '&signature=' + url_data['sig'][0]
  1318. elif 's' in url_data:
  1319. encrypted_sig = url_data['s'][0]
  1320. if self._downloader.params.get('verbose'):
  1321. if age_gate:
  1322. if player_url is None:
  1323. player_version = 'unknown'
  1324. else:
  1325. player_version = self._search_regex(
  1326. r'-(.+)\.swf$', player_url,
  1327. u'flash player', fatal=False)
  1328. player_desc = 'flash player %s' % player_version
  1329. else:
  1330. player_version = self._search_regex(
  1331. r'html5player-(.+?)\.js', video_webpage,
  1332. 'html5 player', fatal=False)
  1333. player_desc = u'html5 player %s' % player_version
  1334. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1335. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1336. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1337. if not age_gate:
  1338. jsplayer_url_json = self._search_regex(
  1339. r'"assets":.+?"js":\s*("[^"]+")',
  1340. video_webpage, u'JS player URL')
  1341. player_url = json.loads(jsplayer_url_json)
  1342. signature = self._decrypt_signature(
  1343. encrypted_sig, video_id, player_url, age_gate)
  1344. url += '&signature=' + signature
  1345. if 'ratebypass' not in url:
  1346. url += '&ratebypass=yes'
  1347. url_map[url_data['itag'][0]] = url
  1348. video_url_list = self._get_video_url_list(url_map)
  1349. if not video_url_list:
  1350. return
  1351. elif video_info.get('hlsvp'):
  1352. manifest_url = video_info['hlsvp'][0]
  1353. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1354. video_url_list = self._get_video_url_list(url_map)
  1355. if not video_url_list:
  1356. return
  1357. else:
  1358. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1359. results = []
  1360. for itag, video_real_url in video_url_list:
  1361. # Extension
  1362. video_extension = self._video_extensions.get(itag, 'flv')
  1363. video_format = '{0} - {1}{2}'.format(itag if itag else video_extension,
  1364. self._video_dimensions.get(itag, '???'),
  1365. ' ('+self._special_itags[itag]+')' if itag in self._special_itags else '')
  1366. results.append({
  1367. 'id': video_id,
  1368. 'url': video_real_url,
  1369. 'uploader': video_uploader,
  1370. 'uploader_id': video_uploader_id,
  1371. 'upload_date': upload_date,
  1372. 'title': video_title,
  1373. 'ext': video_extension,
  1374. 'format': video_format,
  1375. 'format_id': itag,
  1376. 'thumbnail': video_thumbnail,
  1377. 'description': video_description,
  1378. 'player_url': player_url,
  1379. 'subtitles': video_subtitles,
  1380. 'duration': video_duration,
  1381. 'age_limit': 18 if age_gate else 0,
  1382. 'annotations': video_annotations,
  1383. 'webpage_url': 'https://www.youtube.com/watch?v=%s' % video_id,
  1384. 'view_count': view_count,
  1385. })
  1386. return results
  1387. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1388. IE_DESC = u'YouTube.com playlists'
  1389. _VALID_URL = r"""(?:
  1390. (?:https?://)?
  1391. (?:\w+\.)?
  1392. youtube\.com/
  1393. (?:
  1394. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1395. \? (?:.*?&)*? (?:p|a|list)=
  1396. | p/
  1397. )
  1398. ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
  1399. .*
  1400. |
  1401. ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
  1402. )"""
  1403. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s&page=%s'
  1404. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  1405. _VIDEO_RE = r'href="/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1406. IE_NAME = u'youtube:playlist'
  1407. @classmethod
  1408. def suitable(cls, url):
  1409. """Receives a URL and returns True if suitable for this IE."""
  1410. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1411. def _real_initialize(self):
  1412. self._login()
  1413. def _real_extract(self, url):
  1414. # Extract playlist id
  1415. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1416. if mobj is None:
  1417. raise ExtractorError(u'Invalid URL: %s' % url)
  1418. playlist_id = mobj.group(1) or mobj.group(2)
  1419. # Check if it's a video-specific URL
  1420. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1421. if 'v' in query_dict:
  1422. video_id = query_dict['v'][0]
  1423. if self._downloader.params.get('noplaylist'):
  1424. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  1425. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1426. else:
  1427. self.to_screen(u'Downloading playlist PL%s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1428. # Extract the video ids from the playlist pages
  1429. ids = []
  1430. for page_num in itertools.count(1):
  1431. url = self._TEMPLATE_URL % (playlist_id, page_num)
  1432. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1433. matches = re.finditer(self._VIDEO_RE, page)
  1434. # We remove the duplicates and the link with index 0
  1435. # (it's not the first video of the playlist)
  1436. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1437. ids.extend(new_ids)
  1438. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1439. break
  1440. playlist_title = self._og_search_title(page)
  1441. url_results = [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1442. for vid_id in ids]
  1443. return self.playlist_result(url_results, playlist_id, playlist_title)
  1444. class YoutubeChannelIE(InfoExtractor):
  1445. IE_DESC = u'YouTube.com channels'
  1446. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1447. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1448. _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'
  1449. IE_NAME = u'youtube:channel'
  1450. def extract_videos_from_page(self, page):
  1451. ids_in_page = []
  1452. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1453. if mobj.group(1) not in ids_in_page:
  1454. ids_in_page.append(mobj.group(1))
  1455. return ids_in_page
  1456. def _real_extract(self, url):
  1457. # Extract channel id
  1458. mobj = re.match(self._VALID_URL, url)
  1459. if mobj is None:
  1460. raise ExtractorError(u'Invalid URL: %s' % url)
  1461. # Download channel page
  1462. channel_id = mobj.group(1)
  1463. video_ids = []
  1464. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1465. channel_page = self._download_webpage(url, channel_id)
  1466. if re.search(r'channel-header-autogenerated-label', channel_page) is not None:
  1467. autogenerated = True
  1468. else:
  1469. autogenerated = False
  1470. if autogenerated:
  1471. # The videos are contained in a single page
  1472. # the ajax pages can't be used, they are empty
  1473. video_ids = self.extract_videos_from_page(channel_page)
  1474. else:
  1475. # Download all channel pages using the json-based channel_ajax query
  1476. for pagenum in itertools.count(1):
  1477. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1478. page = self._download_webpage(url, channel_id,
  1479. u'Downloading page #%s' % pagenum)
  1480. page = json.loads(page)
  1481. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1482. video_ids.extend(ids_in_page)
  1483. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1484. break
  1485. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1486. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1487. for video_id in video_ids]
  1488. return self.playlist_result(url_entries, channel_id)
  1489. class YoutubeUserIE(InfoExtractor):
  1490. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1491. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1492. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1493. _GDATA_PAGE_SIZE = 50
  1494. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1495. IE_NAME = u'youtube:user'
  1496. @classmethod
  1497. def suitable(cls, url):
  1498. # Don't return True if the url can be extracted with other youtube
  1499. # extractor, the regex would is too permissive and it would match.
  1500. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1501. if any(ie.suitable(url) for ie in other_ies): return False
  1502. else: return super(YoutubeUserIE, cls).suitable(url)
  1503. def _real_extract(self, url):
  1504. # Extract username
  1505. mobj = re.match(self._VALID_URL, url)
  1506. if mobj is None:
  1507. raise ExtractorError(u'Invalid URL: %s' % url)
  1508. username = mobj.group(1)
  1509. # Download video ids using YouTube Data API. Result size per
  1510. # query is limited (currently to 50 videos) so we need to query
  1511. # page by page until there are no video ids - it means we got
  1512. # all of them.
  1513. video_ids = []
  1514. for pagenum in itertools.count(0):
  1515. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1516. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1517. page = self._download_webpage(gdata_url, username,
  1518. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  1519. try:
  1520. response = json.loads(page)
  1521. except ValueError as err:
  1522. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1523. if 'entry' not in response['feed']:
  1524. # Number of videos is a multiple of self._MAX_RESULTS
  1525. break
  1526. # Extract video identifiers
  1527. ids_in_page = []
  1528. for entry in response['feed']['entry']:
  1529. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  1530. video_ids.extend(ids_in_page)
  1531. # A little optimization - if current page is not
  1532. # "full", ie. does not contain PAGE_SIZE video ids then
  1533. # we can assume that this page is the last one - there
  1534. # are no more ids on further pages - no need to query
  1535. # again.
  1536. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1537. break
  1538. url_results = [
  1539. self.url_result(video_id, 'Youtube', video_id=video_id)
  1540. for video_id in video_ids]
  1541. return self.playlist_result(url_results, playlist_title=username)
  1542. class YoutubeSearchIE(SearchInfoExtractor):
  1543. IE_DESC = u'YouTube.com searches'
  1544. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1545. _MAX_RESULTS = 1000
  1546. IE_NAME = u'youtube:search'
  1547. _SEARCH_KEY = 'ytsearch'
  1548. def report_download_page(self, query, pagenum):
  1549. """Report attempt to download search page with given number."""
  1550. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1551. def _get_n_results(self, query, n):
  1552. """Get a specified number of results for a query"""
  1553. video_ids = []
  1554. pagenum = 0
  1555. limit = n
  1556. while (50 * pagenum) < limit:
  1557. self.report_download_page(query, pagenum+1)
  1558. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1559. request = compat_urllib_request.Request(result_url)
  1560. try:
  1561. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1562. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1563. raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
  1564. api_response = json.loads(data)['data']
  1565. if not 'items' in api_response:
  1566. raise ExtractorError(u'[youtube] No video results')
  1567. new_ids = list(video['id'] for video in api_response['items'])
  1568. video_ids += new_ids
  1569. limit = min(n, api_response['totalItems'])
  1570. pagenum += 1
  1571. if len(video_ids) > n:
  1572. video_ids = video_ids[:n]
  1573. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1574. for video_id in video_ids]
  1575. return self.playlist_result(videos, query)
  1576. class YoutubeSearchDateIE(YoutubeSearchIE):
  1577. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1578. _SEARCH_KEY = 'ytsearchdate'
  1579. IE_DESC = u'YouTube.com searches, newest videos first'
  1580. class YoutubeShowIE(InfoExtractor):
  1581. IE_DESC = u'YouTube.com (multi-season) shows'
  1582. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1583. IE_NAME = u'youtube:show'
  1584. def _real_extract(self, url):
  1585. mobj = re.match(self._VALID_URL, url)
  1586. show_name = mobj.group(1)
  1587. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1588. # There's one playlist for each season of the show
  1589. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1590. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1591. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1592. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1593. """
  1594. Base class for extractors that fetch info from
  1595. http://www.youtube.com/feed_ajax
  1596. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1597. """
  1598. _LOGIN_REQUIRED = True
  1599. _PAGING_STEP = 30
  1600. # use action_load_personal_feed instead of action_load_system_feed
  1601. _PERSONAL_FEED = False
  1602. @property
  1603. def _FEED_TEMPLATE(self):
  1604. action = 'action_load_system_feed'
  1605. if self._PERSONAL_FEED:
  1606. action = 'action_load_personal_feed'
  1607. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1608. @property
  1609. def IE_NAME(self):
  1610. return u'youtube:%s' % self._FEED_NAME
  1611. def _real_initialize(self):
  1612. self._login()
  1613. def _real_extract(self, url):
  1614. feed_entries = []
  1615. # The step argument is available only in 2.7 or higher
  1616. for i in itertools.count(0):
  1617. paging = i*self._PAGING_STEP
  1618. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  1619. u'%s feed' % self._FEED_NAME,
  1620. u'Downloading page %s' % i)
  1621. info = json.loads(info)
  1622. feed_html = info['feed_html']
  1623. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1624. ids = orderedSet(m.group(1) for m in m_ids)
  1625. feed_entries.extend(
  1626. self.url_result(video_id, 'Youtube', video_id=video_id)
  1627. for video_id in ids)
  1628. if info['paging'] is None:
  1629. break
  1630. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1631. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1632. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1633. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1634. _FEED_NAME = 'subscriptions'
  1635. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1636. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1637. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1638. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1639. _FEED_NAME = 'recommended'
  1640. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1641. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1642. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1643. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1644. _FEED_NAME = 'watch_later'
  1645. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1646. _PAGING_STEP = 100
  1647. _PERSONAL_FEED = True
  1648. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1649. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1650. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1651. _FEED_NAME = 'history'
  1652. _PERSONAL_FEED = True
  1653. _PLAYLIST_TITLE = u'Youtube Watch History'
  1654. def _real_extract(self, url):
  1655. webpage = self._download_webpage('https://www.youtube.com/feed/history', u'History')
  1656. data_paging = self._search_regex(r'data-paging="(\d+)"', webpage, u'data-paging')
  1657. # The step is actually a ridiculously big number (like 1374343569725646)
  1658. self._PAGING_STEP = int(data_paging)
  1659. return super(YoutubeHistoryIE, self)._real_extract(url)
  1660. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1661. IE_NAME = u'youtube:favorites'
  1662. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1663. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1664. _LOGIN_REQUIRED = True
  1665. def _real_extract(self, url):
  1666. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1667. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1668. return self.url_result(playlist_id, 'YoutubePlaylist')
  1669. class YoutubeTruncatedURLIE(InfoExtractor):
  1670. IE_NAME = 'youtube:truncated_url'
  1671. IE_DESC = False # Do not list
  1672. _VALID_URL = r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$'
  1673. def _real_extract(self, url):
  1674. raise ExtractorError(
  1675. u'Did you forget to quote the URL? Remember that & is a meta '
  1676. u'character in most shells, so you want to put the URL in quotes, '
  1677. u'like youtube-dl '
  1678. u'\'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\''
  1679. u' (or simply youtube-dl BaW_jenozKc ).',
  1680. expected=True)