youtube.py 77 KB

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