youtube.py 77 KB

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